207

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?

1

18 Answers 18

257

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.

Sign up to request clarification or add additional context in comments.

20 Comments

Would have been even better if it could recursively expand to show everything. It could be lots of text but I would then be possibly to search it for a value deeper in the tree.
PS I am so loving the features of bugaid. downloading trail now and when it expires and i start gauging my eyeballs out will make my boss buy it for me.. :)
Anyone know how to output more than 100 items? I get this after the first 100 have been displayed in the Immediate window: < More... (The first 100 of 335 items were displayed.) >
What exactly is meant by "the immediate window"?
@alex: in Visual Studio, go to Debug > Windows > Immediate - It allows you to enter expressions to be evaluated or executed during debugging
|
83

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: Visual Studio how to serialize object from debugger

5 Comments

This should be upvoted so people can find it more easily. I waded through a lot of similar SO questions before I found this great solution, which allowed me to dump a large List<List<byte>> to an xml text file after the crash of a long-running program with a rare crash problem. Just one addition: when I first ran it I got an error: "Evaluation requires a thread to run temporarily. Use the Watch window to perform the evaluation." After refreshing the watch window, a second attempt to run the command was successful.
Bat_Programmer: you might want to change the first line of your answer, because it suggests that what will be output is a list of objects, whereas what is really being output is a serialized XML representation of a single specified object (variable).
Cannot evaluate expression because the code of the current method is optimized.???
If you have json then you can do the following: File.WriteAllText(@"c:\movie.json", JsonConvert.SerializeObject(movie));
The debugger is unable to evaluate this expression. I am using Visual Studio 2019; I substituted obj with the variable name which is type System.Collections.Generic.List 1[[System.ValueTuple 3[[System.String, System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e],[System.String, System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e],[System.String, System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]], System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7]]
53

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)

5 Comments

The json is not formatted and in order to format it you have to perform few more operations which is annoing. The VS should copy into the clipboard the formatted json straight away. The debugging process could be much smoother.
You can add that as watch expression and copy the unescaped JSON from there.
identifier "System" is undefined
@KeyC0de, you have to open the Immediate console under Debug > Window (Ctrl + Alt + I )
Close but doesn't work for larger objects
32

There is a extension called Object Exporter that does this conveniently.

http://www.omarelabd.net/exporting-objects-from-the-visual-studio-debugger/

Extension: https://visualstudiogallery.msdn.microsoft.com/c6a21c68-f815-4895-999f-cd0885d8774f

3 Comments

Seems to be giving problems for larger list of objects
I love Object Exporter, but it is not supported for newer versions of Visual Studio 2019: VSIXInstaller.NoApplicableSKUsException: This extension is not installable on any currently installed products.
At the time, this was a good option. Sad that it doesn't work with the newer versions.
29

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.

1 Comment

Thanks PMN that helped me as well. By manually expanding the tree (would be nice if there were a right click, expand all) and then copying it to the clipboard, I can then paste it and search for a value I'm looking deep down in the tree.
8

Object Dumper is free and open source extension for Visual Studio and Visual Studio Code.

"Dump as" commands are available via context menu in the Code and Immediate windows.

It's exporting objects to:

  • C# object initialization code,
  • JSON,
  • Visual Basic object initialization code,
  • XML,
  • YAML.

I believe that combined with the Diff tool it can be helpful.

I'm the author of this tool.

1 Comment

well done for the tool. Not only supports newer version of VS (currentuly on vs2022) but also is faster than object exporter. Thanks @yevhen. Just what I was looking for.
4

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; }
}

2 Comments

The thing is, I need to be able to copy all the object contents, and not just some of them. Yes, I could build a complex enough DebbuggerDisplay attribute with the whole object, but any changes to the class would need a change in the attribute as well.
@Farinha What do you want to do with the object? Perhaps could have a property that is the serialized xml version of it.
4

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.)

Comments

3

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/

Comments

1

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.

Comments

1

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));
    }
}

Comments

1

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.

1 Comment

the problem is to copy the object that way you need to expand node by node and I do have 145 nodes
0

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

Comments

0

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.

Comments

0

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

Comments

0

As @OmerRaviv says, you can go to Debug → Windows → Immediate where you can type:

myVariable

(as @bombek pointed out in the comments you don't need the question mark) although as some have found this limits to 100 lines.

I found a better way was to right click the variable → Add Watch, then press the + for anything I wanted to expand, then used @GeneWhitaker's solution, which is Ctrl+A, then copy Ctrl+C and paste into a text editor Ctrl+V.

Comments

0

Regarding Xdebug with VSCode for PHP/WordPress, you can print/copy a variable like this:

error_log(print_r($variable, true));

Execute this command in the debug console.

Comments

-1

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.

3 Comments

Where is this debug terminal ?
By default it's at the bottom of vscode, and should open automatically after you start a debugging sessions. It's next to the terminal window. See the first screenshot here: code.visualstudio.com/Docs/editor/debugging
Here you are talking about VS Code Editor, but the question is about Visual Studio IDE

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.