Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a built-in .NET method for getting all of the properties and values for an object?

Tags:

c#

.net

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.

like image 374
Ben McCormack Avatar asked Apr 28 '10 15:04

Ben McCormack


People also ask

What is get and set method in C#?

The get method returns the value of the variable name . The set method assigns a value to the name variable. The value keyword represents the value we assign to the property. If you don't fully understand it, take a look at the example below.

Are properties methods C#?

Properties. C# properties are class members that expose functionality of methods using the syntax of fields. They simplify the syntax of calling traditional get and set methods (a.k.a. accessor methods). Like methods, they can be static or instance.

What is C# method?

A method is a code block that contains a series of statements. A program causes the statements to be executed by calling the method and specifying any required method arguments. In C#, every executed instruction is performed in the context of a method.

Why do we use get set in C#?

A get property accessor is used to return the property value, and a set property accessor is used to assign a new value.


2 Answers

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);
like image 119
Rex M Avatar answered Sep 29 '22 19:09

Rex M


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.

like image 37
Asad Avatar answered Sep 29 '22 18:09

Asad