1

Is this possible to do in C#?

I have POCO object here is definition:

public class Human
{
    public string Name{get;set;}
    public int Age{get;set;}
    public int Weight{get;set;}
}

I would like to map properties of object Human to string array.

Something like this:

Human hObj = new Human{Name="Xi",Age=16,Weight=50};

Or I can have List<Human>:

string [] props = new string [COUNT OF hObj PROPERTIES];

foreach(var prop in hObj PROPERTIES)
{
    props["NAME OF PROPERTIES"] = hObj PROPERTIES VALUE    
}

2 Answers 2

2

It should be something like this:

var props = new Dictionary<string, object>();
foreach(var prop in hObj.GetType().GetProperties(BindingFlags.Public|BindingFlags.Instance);)
{
    props.Add(prop.Name, prop.GetValue(hObj, null));
}

see here for info on GetProperties and here for PropertyInfo

Sign up to request clarification or add additional context in comments.

1 Comment

As noted, Reflection will get you the desired result. Please keep in mind that Reflection isn't very efficient and will result in a noticeable performance hit if your lists get very big.
0

You can use reflection to get an object's properties and values:

var properties = typeof(Human).GetProperties();

IList<KeyValuePair<string, object>> propertyValues = new List<KeyValuePair<string, object>>();

foreach (var propertyInfo in properties)
{
    propertyValues.Add(propertyInfo.Name, propertyInfo.GetValue(oneHuman));
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.