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.
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.
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.
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.
A get property accessor is used to return the property value, and a set property accessor is used to assign a new value.
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);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With