tags:

views:

78

answers:

4

Let's say I have:

public class Item
{
    public string SKU {get; set; }
    public string Description {get; set; }
}

....

Is there a built-in method in .NET that will let me get the properties and values for variable i of type Item that might look like this:

{SKU: "123-4556", Description: "Millennial Radio Classic"}

I know that .ToString() can be overloaded to provide this functionaility, but I couldn't remember if this was already provided in .NET.

+5  A: 

The format you've described as an example looks a lot like JSON, so you could use the JavaScriptSerializer:

string value = new JavaScriptSerializer().Serialize(myItem);
Rex M
I guess my brain has been in JSON mode lately. I'm really just looking for an easy way to print out an object in the console, but yes, it definately looks like JSON.
Ben McCormack
A: 

You could use a JSON library such as JSON.NET or the built-in JavaScriptSerializer.

Darin Dimitrov
+4  A: 

If it is not JSON you are using and just normal C# class, have alook at System.Reflection namespace

something similar would work

Item item = new Item();
foreach (PropertyInfo info in item.GetType().GetProperties())
{
   if (info.CanRead)
   {

      // To retrieve value 
      object o = info.GetValue(myObject, null);

      // To Set Value
      info.SetValue("SKU", "NewValue", null);
   }
}

Provided with, you should have proper get and set in place for the properties you want to work over.

Asad Butt
+1  A: 

The XMLSerializer will work as well: http://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlserializer.aspx

Eric Mickelsen