govin
govin

Reputation: 6733

converting value types of an object to Dictionary<string, string>

How do I iterate through all the value types of an object and convert that into a Dictionary? I was heading the reflection way

obj.GetType().GetProperties()

but that gives both value types and references types.

Upvotes: 1

Views: 101

Answers (1)

Simon Whitehead
Simon Whitehead

Reputation: 65117

You can just use the IsValueType property of the PropertyInfo Type:

obj.GetType().GetProperties().Where(x => x.PropertyType.IsValueType)

Adding it to a dictionary becomes:

foreach (var propertyInfo in obj.GetType().GetProperties().Where(x => x.PropertyType.IsValueType)) {
    dictionary.Add(propertyInfo.Name, propertyInfo.GetValue(obj));
}

Where the key is the name and the value is the value in the obj instance.

Upvotes: 2

Related Questions