Copy object values in Visual Studio debug mode

Visual StudioVisual Studio-2010Debugging

Visual Studio Problem Overview


In Visual Studio debug mode it's possible to hover over variables to show their value and then right-click to "Copy", "Copy Expression" or "Copy Value".

In case the variable is an object and not just a basic type, there's a + sign to expand and explore the object. It there a way to copy all that into the clipboard?

Visual Studio Solutions


Solution 1 - Visual Studio

In the immediate window, type

?name_of_variable

This will print out everything, and you can manually copy that anywhere you want, or use the immediate window's logging features to automatically write it to a file.

UPDATE: I assume you were asking how to copy/paste the nested structure of the values so that you could either search it textually, or so that you can save it on the side and then later compare the object's state to it. If I'm right, you might want to check out the commercial extension to Visual Studio that I created, called OzCode, which lets you do these thing much more easily through the "Search" and "Compare" features.

UPDATE 2 To answer @ppumkin's question, our new EAP has a new Export feature allows users to Export the variable values to Json, XML, Excel, or C# code.

Full disclosure: I'm the co-creator of the tool I described here.

Solution 2 - Visual Studio

You can run below code in immediate window and it will export to an xml file the serialized XML representation of an object:

(new System.Xml.Serialization.XmlSerializer(obj.GetType())).Serialize(new System.IO.StreamWriter(@"c:\temp\text.xml"), obj)

Source: https://stackoverflow.com/questions/18794264/visual-studio-how-to-serialize-object-from-debugger

Solution 3 - Visual Studio

Most popular answer from https://stackoverflow.com/a/23362097/2680660:

> With any luck you have Json.Net in you appdomain already. In which > case pop this into your Immediate window: > > Newtonsoft.Json.JsonConvert.SerializeObject(someVariable)

Edit: With .NET Core 3.0, the following works too:

System.Text.Json.JsonSerializer.Serialize(someVariable)

Solution 4 - Visual Studio

Solution 5 - Visual Studio

You can add a watch for that object, and in the watch window, expand and select everything you want to copy and then copy it.

Solution 6 - Visual Studio

By using attributes to decorate your classes and methods you can have a specific value from your object display during debugging with the DebuggerDisplay attribute e.g.

[DebuggerDisplay("Person - {Name} is {Age} years old")]
public class Person
{
  public string Name { get; set; }
  public int Age { get; set; }
}

Solution 7 - Visual Studio

I always use:

string myJsonString = JsonConvert.SerializeObject(<some object>);

Then I copy the string value which unfortunately also copies the back slashes.

To remove the backlashes go here: https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_replace

Then within the <p id="demo">Visit Microsoft!</p> element replace the text with the text you copied. then replace the var res = str.replace("Microsoft", "W3Schools"); line with

var res = str.replace(/\\/g, '')

Run these new changes but don't forget to click the "try it" button on the right.

Now you should have all the text of the object in json format that you can drop in a json formatter like http://jsonformatter.org or to create a POCO you can now use http://json2csharp.com/

Solution 8 - Visual Studio

Google led me to this 8-year-old question and I ended up using ObjectDumper to achieve something very similar to copy-pasting debugger data. It was a breeze.

I know the question asked specifically about information from the debugger, but ObjectDumper gives information that is basically the same. I'm assuming those who google this question are like me and just need the data for debugging purposes and don't care whether it technically comes from the debugger or not.

Solution 9 - Visual Studio

I know I'm a bit late to the party, but I wrote a JSON implementation for serializing an object, if you prefer to have JSON output. Uses Newtonsoft.Json reference.

private static void WriteDebugJSON (dynamic obj, string filePath)
{
    using (StreamWriter d = new StreamWriter(filePath))
    {
        d.Write(JsonConvert.SerializeObject(obj));
    }
}

Solution 10 - Visual Studio

if you have a list and you want to find a specific variable: In the immediate window, type

 myList.Any(s => s.ID == 5062);

if this returns true

var myDebugVar = myList.FirstOrDefault(s => s.ID == 5062);
?myDebugVar

Solution 11 - Visual Studio

I've just right clicked on the variable and selected AddWatch, that's bring up watch window that consists of all the values. I selected all and paste it in a text a text editor, that's all.

Solution 12 - Visual Studio

useful tips here, I'll add my preference for when i next end up here asking this question again in the future. if you don't mind adding an extension that doesn't require output files or such there's the Hex Visualizer extension for visual studio, by mladen mihajlovic, he's done versions since 2015. provides a nice display of the array via the usual magnifine glass view object from the local variables window. https://marketplace.visualstudio.com/items?itemName=Mika76.HexVisualizer2019 is the 2019 version.

Solution 13 - Visual Studio

If you're in debug mode, you can copy any variable by writing copy() in the debug terminal.

This works with nested objects and also removes truncation and copies the complete value.

Tip: you can right click a variable, and click Copy as Expression and then paste that in the copy-function.

Solution 14 - Visual Studio

ObjectDumper.NET

This is an awesome way!

  1. You probably need this data for a unit test, so create a Sandbox.cs temporary test or you can create a Console App.
  2. Make sure to get NuGet package, ObjectDumper.NET, not ObjectDumper.
  3. Run this test (or console app)
  4. View test output or text file to get the C# initializer code!

Code:

[TestClass]
public class Sandbox
{
    [TestMethod]
    public void GetInitializerCode()
    {
        var db = TestServices.GetDbContext();
        var list = db.MyObjects.ToList();
        var literal = ObjectDumper.Dump(list, new DumpOptions
        {
            DumpStyle = DumpStyle.CSharp,
            IndentSize = 4
        });
        Console.WriteLine(literal); // Some test runners will truncate this, so use the file in that case.
        File.WriteAllText(@"C:\temp\dump.txt", literal);
    }
}

I used to use Object Exporter, but it is 5 years old and no longer supported in Visual Studio. It seems like Visual Studio Extensions come and go, but let's hope this NuGet package is here to stay! (Also it is actively maintained as of this writing.)

Solution 15 - Visual Studio

System.IO.File.WriteAllText("b.json", page.DebugInfo().ToJson()) Works great to avoid to deal with string debug format " for quote.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionFarinhaView Question on Stackoverflow
Solution 1 - Visual StudioOmer RavivView Answer on Stackoverflow
Solution 2 - Visual StudioBat_ProgrammerView Answer on Stackoverflow
Solution 3 - Visual StudioEfreetoView Answer on Stackoverflow
Solution 4 - Visual StudioAnimeshView Answer on Stackoverflow
Solution 5 - Visual StudioPMNView Answer on Stackoverflow
Solution 6 - Visual StudioDave AndersonView Answer on Stackoverflow
Solution 7 - Visual StudioPost ImpaticaView Answer on Stackoverflow
Solution 8 - Visual StudioJesse HufstetlerView Answer on Stackoverflow
Solution 9 - Visual StudioMarcus ParsonsView Answer on Stackoverflow
Solution 10 - Visual Studioemert117View Answer on Stackoverflow
Solution 11 - Visual StudioagileDevView Answer on Stackoverflow
Solution 12 - Visual StudioAllisterView Answer on Stackoverflow
Solution 13 - Visual StudioJohnDoeView Answer on Stackoverflow
Solution 14 - Visual StudioJessView Answer on Stackoverflow
Solution 15 - Visual StudioRemi THOMASView Answer on Stackoverflow