186

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?

Farinha
  • 17,636
  • 21
  • 64
  • 80
  • With quickwatch and Buildin tools it's easy: [My take on this is issue](https://stackoverflow.com/a/71659830/12058671) – Dominik Sand Mar 29 '22 at 09:56

17 Answers17

240

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.

Jess
  • 23,901
  • 21
  • 124
  • 145
Omer Raviv
  • 11,409
  • 5
  • 43
  • 82
  • 1
    Perfect! This outputs only the values and not all the variable types that are shown in a Watch. – Farinha May 31 '10 at 10:42
  • 5
    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. – Kobus Smit Mar 17 '11 at 11:42
  • @KobusSmit I've updated my post with a way that you can do that. – Omer Raviv Jan 06 '12 at 07:00
  • @OmerRaviv Thanks, congrats BugAid looks like an awesomely useful debugging extension! – Kobus Smit Jan 20 '12 at 12:40
  • If object is complex it does not show all the inner object.. dammit so close but so far.. – Piotr Kula Oct 25 '12 at 09:30
  • 3
    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.. :) – Piotr Kula Oct 25 '12 at 09:35
  • PSS If you could implement an object dump - to XML, CSV-TAB, SQL Statements...? Instaead of me going into code, putting in a block to serialize something, run the code and copy the XML and then un-checkout somebodies project.. that is FAST! Ill buy it just for that :) – Piotr Kula Oct 25 '12 at 09:46
  • @ppumkin We definitely plan to do that, please vote for this at: http://bugaidsoftware.userecho.com/topic/56113-save-variables-to-file/ – Omer Raviv Apr 11 '13 at 19:21
  • 1
    I just used this to solve one of my problem of: How to compare the locals stack to another version of the locals stack. I added the variables to a custom class which each had place holders for their types, and compared that object using the Compare feature. – Seann Alexander Nov 18 '14 at 19:57
  • 1
    I'd say it's a _co_ disclosure – JNF Apr 15 '15 at 05:14
  • 23
    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.) > – lachs Jan 19 '16 at 05:50
  • 13
    What exactly is meant by "the immediate window"? – alex Feb 12 '16 at 18:14
  • 7
    @alex: in Visual Studio, go to Debug > Windows > Immediate - It allows you to enter expressions to be evaluated or executed during debugging – JTech Jan 09 '17 at 03:45
  • 2
    Looks like M$ broke this. In VS2019, copying the value or typing `?variable` in the immediate window produces a string that is shortened with an ellipsis. – StackOverthrow Sep 23 '19 at 16:56
  • 2
    @lachs Not directly, but this helped me copy stuff with more than 100 items: https://stackoverflow.com/questions/1785745/visual-studio-immediate-window-how-to-see-more-than-the-first-100-items – Charlie Su Dec 27 '19 at 22:01
  • 2
    Actually you don't need a "?" before variable name. – bombek May 20 '20 at 10:07
  • I got here because I need to create test data for my unit tests (similar to what gets otherwise loaded from database) and the OzCode object dump feature is great for that! One click and I had a list of 80+ complex object instances as C# code. Just the bool scripting as "true" / "false" (with double quotes) is weird. – IngoB May 29 '20 at 19:13
  • Thank you for the OzCode extension. However, the search functionality doesn't seem to work. I search for something called "Level" it says it didn't find anything so I try searching deeper, it still shows 0 out of 0, but then I expand some properties and see it highlighted. Any ideas why it's behaving like that? @OmerRaviv – Ondrej Tokar Feb 14 '21 at 09:56
  • Also the export function doesn't seem to be doing anything. Nor can I copy the entire model/object payload :(. – Ondrej Tokar Feb 14 '21 at 09:59
79

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

Community
  • 1
  • 1
Bat_Programmer
  • 6,717
  • 10
  • 56
  • 67
  • 6
    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> 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. – Craig.Feied Jan 16 '17 at 23:22
  • 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). – Craig.Feied Jan 16 '17 at 23:27
  • `Cannot evaluate expression because the code of the current method is optimized.`??? – Falco Alexander Apr 26 '19 at 10:08
  • 5
    If you have json then you can do the following: `File.WriteAllText(@"c:\movie.json", JsonConvert.SerializeObject(movie));` – user890332 Sep 08 '19 at 14:30
  • `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]]` – Drew Jan 23 '20 at 21:49
48

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)
Efreeto
  • 2,132
  • 1
  • 24
  • 25
31

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

Jess
  • 23,901
  • 21
  • 124
  • 145
Animesh
  • 4,926
  • 14
  • 68
  • 110
  • 1
    Seems to be giving problems for larger list of objects – Bat_Programmer Dec 16 '16 at 01:02
  • 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.` – Jess Oct 08 '21 at 14:56
  • 1
    At the time, this was a good option. Sad that it doesn't work with the newer versions. – Animesh Oct 08 '21 at 18:02
28

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.

RJFalconer
  • 10,890
  • 5
  • 51
  • 66
PMN
  • 1,721
  • 13
  • 10
  • 1
    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. – Kobus Smit Mar 17 '11 at 11:44
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; }
}
Dave Anderson
  • 11,836
  • 3
  • 58
  • 79
  • 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 May 28 '10 at 10:11
  • @Farinha What do you want to do with the object? Perhaps could have a property that is the serialized xml version of it. – Dave Anderson May 28 '10 at 11:18
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/

Post Impatica
  • 14,999
  • 9
  • 67
  • 78
3

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

halfer
  • 19,824
  • 17
  • 99
  • 186
Jess
  • 23,901
  • 21
  • 124
  • 145
2

Object Dumper is a 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.

Yevhen Cherkes
  • 626
  • 7
  • 10
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.

Jesse Hufstetler
  • 583
  • 7
  • 13
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));
    }
}
Marcus Parsons
  • 1,714
  • 13
  • 19
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.

agileDev
  • 423
  • 5
  • 14
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
emert117
  • 1,268
  • 2
  • 20
  • 38
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.

Allister
  • 189
  • 1
  • 5
0

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.

JohnDoe
  • 507
  • 7
  • 21
0

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

Remi THOMAS
  • 854
  • 6
  • 11
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.

SharpC
  • 6,974
  • 4
  • 45
  • 40