serdar
serdar

Reputation: 1618

Is it possible to get the object from debug mode as string?

To test a class I need some dummy objects which are realistic.

My question is that: While debugging can I get an already constructed object as string? I want to copy this string and paste(assign) it to the dummy object in the test class.

public class Employee
{
    public string Name;
    public int Age;
    public List<string> NamesOfChildren;
}

For example for an instance of this class in debug mode I need some string like

new Employee() {Name = "Serdar", Age = 30, NamesOfChildren = new List() {"NameOfChild1", "NameOfChild2"}}

In other words in debug mode I can see all public and private fields and their values of an object. Can I take this data as string? I need it in the format of creating that object in the editor. (Of course only public fields)

Upvotes: 0

Views: 511

Answers (1)

Rafael Merlin
Rafael Merlin

Reputation: 2767

I'm not sure about the private fields, but I believe the Json.NET can help you. You're going to have to add the object name, but I believe you can automate this easily.

You can install it using Nuget: Install-Package Newtonsoft.Json

You can find more information at: http://james.newtonking.com/json

Here is a example their site has:

Product product = new Product();
product.Name = "Apple";
product.Expiry = new DateTime(2008, 12, 28);
product.Sizes = new string[] { "Small" };

string json = JsonConvert.SerializeObject(product);
//{
//  "Name": "Apple",
//  "Expiry": "2008-12-28T00:00:00",
//  "Sizes": [
//    "Small"
//  ]
//}

The same idea goes for Deserializing the object:

string json = @"{
  'Name': 'Bad Boys',
  'ReleaseDate': '1995-4-7T00:00:00',
  'Genres': [
    'Action',
    'Comedy'
  ]
}";

Movie m = JsonConvert.DeserializeObject<Movie>(json);

string name = m.Name;
// Bad Boys

Upvotes: 2

Related Questions