Listing object properties like the Visual Studio Immediate window - c#

I store a few classes in session. I want to be able to see the values of my class properties in trace viewer. By default I only the Type name MyNamespace.MyClass. I was wondering if I overwrite the .ToString() method and use reflection to loop over all the properties and construct a string like that ... it would do the trick but just wanted to see if there is anything already out there (specially since Immediate Window has this capability) which does the same ... i.e. list the class property values in trace instead of just the Name of the class.

You can try something like that:
static void Dump(object o, TextWriter output)
{
if (o == null)
{
output.WriteLine("null");
return;
}
var properties =
from prop in o.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public)
where prop.CanRead
&& !prop.GetIndexParameters().Any() // exclude indexed properties to keep things simple
select new
{
prop.Name,
Value = prop.GetValue(o, null)
};
output.WriteLine(o.ToString());
foreach (var prop in properties)
{
output.WriteLine(
"\t{0}: {1}",
prop.Name,
(prop.Value ?? "null").ToString());
}
}
Of course, it's not very efficient because of the reflection... A better solution would be to dynamically generate and cache a dumper method for each specific type.
EDIT: here's an improved solution, that uses Linq expressions to generate a specialized dumper method for each type. Slightly more complex ;)
static class Dumper
{
private readonly static Dictionary<Type, Action<object, TextWriter>> _dumpActions
= new Dictionary<Type, Action<object, TextWriter>>();
private static Action<object, TextWriter> CreateDumper(Type type)
{
MethodInfo writeLine1Obj = typeof(TextWriter).GetMethod("WriteLine", new[] { typeof(object) });
MethodInfo writeLine1String2Obj = typeof(TextWriter).GetMethod("WriteLine", new[] { typeof(string), typeof(object), typeof(object) });
ParameterExpression objParam = Expression.Parameter(typeof(object), "o");
ParameterExpression outputParam = Expression.Parameter(typeof(TextWriter), "output");
ParameterExpression objVariable = Expression.Variable(type, "o2");
LabelTarget returnTarget = Expression.Label();
List<Expression> bodyExpressions = new List<Expression>();
bodyExpressions.Add(
// o2 = (<type>)o
Expression.Assign(objVariable, Expression.Convert(objParam, type)));
bodyExpressions.Add(
// output.WriteLine(o)
Expression.Call(outputParam, writeLine1Obj, objParam));
var properties =
from prop in type.GetProperties(BindingFlags.Instance | BindingFlags.Public)
where prop.CanRead
&& !prop.GetIndexParameters().Any() // exclude indexed properties to keep things simple
select prop;
foreach (var prop in properties)
{
bool isNullable =
!prop.PropertyType.IsValueType ||
prop.PropertyType.IsGenericType && prop.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>);
// (object)o2.<property> (cast to object to be passed to WriteLine)
Expression propValue =
Expression.Convert(
Expression.Property(objVariable, prop),
typeof(object));
if (isNullable)
{
// (<propertyValue> ?? "null")
propValue =
Expression.Coalesce(
propValue,
Expression.Constant("null", typeof(object)));
}
bodyExpressions.Add(
// output.WriteLine("\t{0}: {1}", "<propertyName>", <propertyValue>)
Expression.Call(
outputParam,
writeLine1String2Obj,
Expression.Constant("\t{0}: {1}", typeof(string)),
Expression.Constant(prop.Name, typeof(string)),
propValue));
}
bodyExpressions.Add(Expression.Label(returnTarget));
Expression<Action<object, TextWriter>> dumperExpr =
Expression.Lambda<Action<object, TextWriter>>(
Expression.Block(new[] { objVariable }, bodyExpressions),
objParam,
outputParam);
return dumperExpr.Compile();
}
public static void Dump(object o, TextWriter output)
{
if (o == null)
{
output.WriteLine("null");
}
Type type = o.GetType();
Action<object, TextWriter> dumpAction;
if (!_dumpActions.TryGetValue(type, out dumpAction))
{
dumpAction = CreateDumper(type);
_dumpActions[type] = dumpAction;
}
dumpAction(o, output);
}
}
Usage:
Dumper.Dump(myObject, Console.Out);

This is the code I use. I find it incredibly useful and is almost instant. The code is using the Newtonsoft JSON converter.
[System.Obsolete("ObjectDump should not be included in production code.")]
public static void Dump(this object value)
{
try
{
System.Diagnostics.Trace.WriteLine(JsonConvert.SerializeObject(value, Formatting.Indented));
}
catch (Exception exception)
{
System.Diagnostics.Trace.WriteLine("Object could not be formatted. Does it include any interfaces? Exception Message: " + exception.Message);
}
}
Add this to a common library, reference it and add it to the using clause. Can be used in the immediate window by typing YourObject.Dump() (the exact same as you'd do in linqpad).
Classes including interfaces have to be handled differently as this is simply a JSON converter. A workaround for classes that include interface implementations that I use is to remove the default empty constructor and implement a constructor using the specific instances of the interfaces.
I find JSON a very easy format to read and consider this small method invaluable for debugging.

Related

Is there a way to build a new object feeding it properties step by step in a loop in C#? [duplicate]

Is there a way in C# where I can use reflection to set an object property?
Ex:
MyObject obj = new MyObject();
obj.Name = "Value";
I want to set obj.Name with reflection. Something like:
Reflection.SetProperty(obj, "Name") = "Value";
Is there a way of doing this?
Yes, you can use Type.InvokeMember():
using System.Reflection;
MyObject obj = new MyObject();
obj.GetType().InvokeMember("Name",
BindingFlags.Instance | BindingFlags.Public | BindingFlags.SetProperty,
Type.DefaultBinder, obj, "Value");
This will throw an exception if obj doesn't have a property called Name, or it can't be set.
Another approach is to get the metadata for the property, and then set it. This will allow you to check for the existence of the property, and verify that it can be set:
using System.Reflection;
MyObject obj = new MyObject();
PropertyInfo prop = obj.GetType().GetProperty("Name", BindingFlags.Public | BindingFlags.Instance);
if(null != prop && prop.CanWrite)
{
prop.SetValue(obj, "Value", null);
}
You can also do:
Type type = target.GetType();
PropertyInfo prop = type.GetProperty("propertyName");
prop.SetValue (target, propertyValue, null);
where target is the object that will have its property set.
Reflection, basically, i.e.
myObject.GetType().GetProperty(property).SetValue(myObject, "Bob", null);
or there are libraries to help both in terms of convenience and performance; for example with FastMember:
var wrapped = ObjectAccessor.Create(obj);
wrapped[property] = "Bob";
(which also has the advantage of not needing to know in advance whether it is a field vs a property)
Or you could wrap Marc's one liner inside your own extension class:
public static class PropertyExtension{
public static void SetPropertyValue(this object obj, string propName, object value)
{
obj.GetType().GetProperty(propName).SetValue(obj, value, null);
}
}
and call it like this:
myObject.SetPropertyValue("myProperty", "myValue");
For good measure, let's add a method to get a property value:
public static object GetPropertyValue(this object obj, string propName)
{
return obj.GetType().GetProperty(propName).GetValue (obj, null);
}
Use somethings like this :
public static class PropertyExtension{
public static void SetPropertyValue(this object p_object, string p_propertyName, object value)
{
PropertyInfo property = p_object.GetType().GetProperty(p_propertyName);
property.SetValue(p_object, Convert.ChangeType(value, property.PropertyType), null);
}
}
or
public static class PropertyExtension{
public static void SetPropertyValue(this object p_object, string p_propertyName, object value)
{
PropertyInfo property = p_object.GetType().GetProperty(p_propertyName);
Type t = Nullable.GetUnderlyingType(property.PropertyType) ?? property.PropertyType;
object safeValue = (value == null) ? null : Convert.ChangeType(value, t);
property.SetValue(p_object, safeValue, null);
}
}
Yes, using System.Reflection:
using System.Reflection;
...
string prop = "name";
PropertyInfo pi = myObject.GetType().GetProperty(prop);
pi.SetValue(myObject, "Bob", null);
You can also access fields using a simillar manner:
var obj=new MyObject();
FieldInfo fi = obj.GetType().
GetField("Name", BindingFlags.NonPublic | BindingFlags.Instance);
fi.SetValue(obj,value)
With reflection everything can be an open book:) In my example we are binding to a private instance level field.
You can try this out when you want to mass-assign properties of an Object from another Object using Property names:
public static void Assign(this object destination, object source)
{
if (destination is IEnumerable && source is IEnumerable)
{
var dest_enumerator = (destination as IEnumerable).GetEnumerator();
var src_enumerator = (source as IEnumerable).GetEnumerator();
while (dest_enumerator.MoveNext() && src_enumerator.MoveNext())
dest_enumerator.Current.Assign(src_enumerator.Current);
}
else
{
var destProperties = destination.GetType().GetProperties();
foreach (var sourceProperty in source.GetType().GetProperties())
{
foreach (var destProperty in destProperties)
{
if (destProperty.Name == sourceProperty.Name && destProperty.PropertyType.IsAssignableFrom(sourceProperty.PropertyType))
{
destProperty.SetValue(destination, sourceProperty.GetValue(source, new object[] { }), new object[] { });
break;
}
}
}
}
I have just published a Nuget package that allows setting up not only the first level Properties but also nested properties in the given object in any depth.
Here is the package
Sets the value of a property of an object by its path from the root.
The object can be a complex object and the property can be multi level deep nested property or it can be a property directly under the root. ObjectWriter will find the property using the property path parameter and update its value. Property path is the appended names of the properties visited from root to the end node property which we want to set, delimited by the delimiter string parameter.
Usage:
For setting up the properties directly under the object root:
Ie. LineItem class has an int property called ItemId
LineItem lineItem = new LineItem();
ObjectWriter.Set(lineItem, "ItemId", 13, delimiter: null);
For setting up nested property multiple levels below the object root:
Ie. Invite class has a property called State, which has a property called Invite (of Invite type), which has a property called Recipient, which has a property called Id.
To make things even more complex, the State property is not a reference type, it is a struct.
Here is how you can set the Id property (to string value of “outlook”) at the bottom of the object tree in a single line.
Invite invite = new Invite();
ObjectWriter.Set(invite, "State_Invite_Recipient_Id", "outlook", delimiter: "_");
Based on MarcGravell's suggestion, I have constructed the following static method.The method generically assigns all matching properties from source object to target using FastMember
public static void DynamicPropertySet(object source, object target)
{
//SOURCE
var src_accessor = TypeAccessor.Create(source.GetType());
if (src_accessor == null)
{
throw new ApplicationException("Could not create accessor!");
}
var src_members = src_accessor.GetMembers();
if (src_members == null)
{
throw new ApplicationException("Could not fetch members!");
}
var src_class_members = src_members.Where(x => x.Type.IsClass && !x.Type.IsPrimitive);
var src_class_propNames = src_class_members.Select(x => x.Name);
var src_propNames = src_members.Except(src_class_members).Select(x => x.Name);
//TARGET
var trg_accessor = TypeAccessor.Create(target.GetType());
if (trg_accessor == null)
{
throw new ApplicationException("Could not create accessor!");
}
var trg_members = trg_accessor.GetMembers();
if (trg_members == null)
{
throw new ApplicationException("Could not create accessor!");
}
var trg_class_members = trg_members.Where(x => x.Type.IsClass && !x.Type.IsPrimitive);
var trg_class_propNames = trg_class_members.Select(x => x.Name);
var trg_propNames = trg_members.Except(trg_class_members).Select(x => x.Name);
var class_propNames = trg_class_propNames.Intersect(src_class_propNames);
var propNames = trg_propNames.Intersect(src_propNames);
foreach (var propName in propNames)
{
trg_accessor[target, propName] = src_accessor[source, propName];
}
foreach (var member in class_propNames)
{
var src = src_accessor[source, member];
var trg = trg_accessor[target, member];
if (src != null && trg != null)
{
DynamicPropertySet(src, trg);
}
}
}

C# - How to change value for property using reflection? [duplicate]

Is there a way in C# where I can use reflection to set an object property?
Ex:
MyObject obj = new MyObject();
obj.Name = "Value";
I want to set obj.Name with reflection. Something like:
Reflection.SetProperty(obj, "Name") = "Value";
Is there a way of doing this?
Yes, you can use Type.InvokeMember():
using System.Reflection;
MyObject obj = new MyObject();
obj.GetType().InvokeMember("Name",
BindingFlags.Instance | BindingFlags.Public | BindingFlags.SetProperty,
Type.DefaultBinder, obj, "Value");
This will throw an exception if obj doesn't have a property called Name, or it can't be set.
Another approach is to get the metadata for the property, and then set it. This will allow you to check for the existence of the property, and verify that it can be set:
using System.Reflection;
MyObject obj = new MyObject();
PropertyInfo prop = obj.GetType().GetProperty("Name", BindingFlags.Public | BindingFlags.Instance);
if(null != prop && prop.CanWrite)
{
prop.SetValue(obj, "Value", null);
}
You can also do:
Type type = target.GetType();
PropertyInfo prop = type.GetProperty("propertyName");
prop.SetValue (target, propertyValue, null);
where target is the object that will have its property set.
Reflection, basically, i.e.
myObject.GetType().GetProperty(property).SetValue(myObject, "Bob", null);
or there are libraries to help both in terms of convenience and performance; for example with FastMember:
var wrapped = ObjectAccessor.Create(obj);
wrapped[property] = "Bob";
(which also has the advantage of not needing to know in advance whether it is a field vs a property)
Or you could wrap Marc's one liner inside your own extension class:
public static class PropertyExtension{
public static void SetPropertyValue(this object obj, string propName, object value)
{
obj.GetType().GetProperty(propName).SetValue(obj, value, null);
}
}
and call it like this:
myObject.SetPropertyValue("myProperty", "myValue");
For good measure, let's add a method to get a property value:
public static object GetPropertyValue(this object obj, string propName)
{
return obj.GetType().GetProperty(propName).GetValue (obj, null);
}
Use somethings like this :
public static class PropertyExtension{
public static void SetPropertyValue(this object p_object, string p_propertyName, object value)
{
PropertyInfo property = p_object.GetType().GetProperty(p_propertyName);
property.SetValue(p_object, Convert.ChangeType(value, property.PropertyType), null);
}
}
or
public static class PropertyExtension{
public static void SetPropertyValue(this object p_object, string p_propertyName, object value)
{
PropertyInfo property = p_object.GetType().GetProperty(p_propertyName);
Type t = Nullable.GetUnderlyingType(property.PropertyType) ?? property.PropertyType;
object safeValue = (value == null) ? null : Convert.ChangeType(value, t);
property.SetValue(p_object, safeValue, null);
}
}
Yes, using System.Reflection:
using System.Reflection;
...
string prop = "name";
PropertyInfo pi = myObject.GetType().GetProperty(prop);
pi.SetValue(myObject, "Bob", null);
You can also access fields using a simillar manner:
var obj=new MyObject();
FieldInfo fi = obj.GetType().
GetField("Name", BindingFlags.NonPublic | BindingFlags.Instance);
fi.SetValue(obj,value)
With reflection everything can be an open book:) In my example we are binding to a private instance level field.
You can try this out when you want to mass-assign properties of an Object from another Object using Property names:
public static void Assign(this object destination, object source)
{
if (destination is IEnumerable && source is IEnumerable)
{
var dest_enumerator = (destination as IEnumerable).GetEnumerator();
var src_enumerator = (source as IEnumerable).GetEnumerator();
while (dest_enumerator.MoveNext() && src_enumerator.MoveNext())
dest_enumerator.Current.Assign(src_enumerator.Current);
}
else
{
var destProperties = destination.GetType().GetProperties();
foreach (var sourceProperty in source.GetType().GetProperties())
{
foreach (var destProperty in destProperties)
{
if (destProperty.Name == sourceProperty.Name && destProperty.PropertyType.IsAssignableFrom(sourceProperty.PropertyType))
{
destProperty.SetValue(destination, sourceProperty.GetValue(source, new object[] { }), new object[] { });
break;
}
}
}
}
I have just published a Nuget package that allows setting up not only the first level Properties but also nested properties in the given object in any depth.
Here is the package
Sets the value of a property of an object by its path from the root.
The object can be a complex object and the property can be multi level deep nested property or it can be a property directly under the root. ObjectWriter will find the property using the property path parameter and update its value. Property path is the appended names of the properties visited from root to the end node property which we want to set, delimited by the delimiter string parameter.
Usage:
For setting up the properties directly under the object root:
Ie. LineItem class has an int property called ItemId
LineItem lineItem = new LineItem();
ObjectWriter.Set(lineItem, "ItemId", 13, delimiter: null);
For setting up nested property multiple levels below the object root:
Ie. Invite class has a property called State, which has a property called Invite (of Invite type), which has a property called Recipient, which has a property called Id.
To make things even more complex, the State property is not a reference type, it is a struct.
Here is how you can set the Id property (to string value of “outlook”) at the bottom of the object tree in a single line.
Invite invite = new Invite();
ObjectWriter.Set(invite, "State_Invite_Recipient_Id", "outlook", delimiter: "_");
Based on MarcGravell's suggestion, I have constructed the following static method.The method generically assigns all matching properties from source object to target using FastMember
public static void DynamicPropertySet(object source, object target)
{
//SOURCE
var src_accessor = TypeAccessor.Create(source.GetType());
if (src_accessor == null)
{
throw new ApplicationException("Could not create accessor!");
}
var src_members = src_accessor.GetMembers();
if (src_members == null)
{
throw new ApplicationException("Could not fetch members!");
}
var src_class_members = src_members.Where(x => x.Type.IsClass && !x.Type.IsPrimitive);
var src_class_propNames = src_class_members.Select(x => x.Name);
var src_propNames = src_members.Except(src_class_members).Select(x => x.Name);
//TARGET
var trg_accessor = TypeAccessor.Create(target.GetType());
if (trg_accessor == null)
{
throw new ApplicationException("Could not create accessor!");
}
var trg_members = trg_accessor.GetMembers();
if (trg_members == null)
{
throw new ApplicationException("Could not create accessor!");
}
var trg_class_members = trg_members.Where(x => x.Type.IsClass && !x.Type.IsPrimitive);
var trg_class_propNames = trg_class_members.Select(x => x.Name);
var trg_propNames = trg_members.Except(trg_class_members).Select(x => x.Name);
var class_propNames = trg_class_propNames.Intersect(src_class_propNames);
var propNames = trg_propNames.Intersect(src_propNames);
foreach (var propName in propNames)
{
trg_accessor[target, propName] = src_accessor[source, propName];
}
foreach (var member in class_propNames)
{
var src = src_accessor[source, member];
var trg = trg_accessor[target, member];
if (src != null && trg != null)
{
DynamicPropertySet(src, trg);
}
}
}

How to generically create an Expression for a property?

ExpressMapper has an Ignore method that looks like this:
public IMemberConfiguration<T, TN> Ignore<TMember>(Expression<Func<TN, TMember>> dest)
{
if (dest == null)
{
throw new ArgumentNullException("dst");
}
if (!(dest.Body is MemberExpression))
{
throw new Exception("MemberExpression should return one of the properties of destination class");
}
foreach (var typeMapper in _typeMappers)
{
typeMapper.Ignore(dest);
}
return this;
}
I would like to add my own IgnoreAll method that iterates over all properties on a Type and calls the Ignore method for each property. This is what I have so far:
public static IMemberConfiguration<TSource, TDestination> IgnoreAll<TSource, TDestination>(
this IMemberConfiguration<TSource, TDestination> config)
{
var props = typeof (TDestination).GetProperties();
foreach (var prop in props)
{
var propertyInfo = typeof(TDestination).GetProperty(prop.Name);
var entityParam = Expression.Parameter(typeof(TDestination), "e");
Expression columnExpr = Expression.Property(entityParam, prop);
if (propertyInfo.PropertyType != typeof(object))
columnExpr = Expression.Convert(columnExpr, typeof(object));
var expression = Expression.Lambda<Func<TDestination, object>>(columnExpr, entityParam);
config.Ignore(expression);
}
return config;
}
When this code is run, I get an error:
MemberExpression should return one of the properties of destination
class
As you can see from the source of the Ignore method above, my generated expression is failing the following conditional:
if (!(dest.Body is MemberExpression))
{
throw new Exception("MemberExpression should return one of the properties of destination class");
}
So my question is:
What do I need to change in my extension method to make the correct Expression that the Ignore method is expecting?
Edit: by the way, the full source for the MemberConfiguration class is here: https://github.com/fluentsprings/ExpressMapper/blob/master/ExpressMapper%20NET40/MemberConfiguration.cs
Okay I figured this out, and I gotta tell ya, it was a doozy.
public static IMemberConfiguration<TSource, TDestination> IgnoreAll<TSource, TDestination>(
this IMemberConfiguration<TSource, TDestination> config)
{
// First we'll get the collection of properties to iterate over.
var props = typeof (TDestination).GetProperties();
foreach (var prop in props)
{
// Get the property information.
var propertyInfo = typeof(TDestination).GetProperty(prop.Name);
// Create an expression that points to the property.
var entityParameter = new ParameterExpression[]
{
Expression.Parameter(typeof(TDestination), "e")
};
var propertyExpression = Expression.Property(entityParameter[0], prop);
// Create a Func<,> using the TDestination and the property's type
// for the Type parameters.
var funcType = typeof(Func<,>).MakeGenericType(typeof(TDestination), propertyInfo.PropertyType);
// We need to create an Expression using Expression.Lambda<>, but we
// don't know the types involved so we have to do this using reflection.
var lambdaMethod = typeof (Expression)
.GetMethods()
.Single(m => m.IsGenericMethod &&
m.GetParameters()[0].ParameterType == typeof(Expression) &&
m.GetParameters()[1].ParameterType == typeof(ParameterExpression[]));
var lambdaMethodConstructed = lambdaMethod.MakeGenericMethod(funcType);
var expression = lambdaMethodConstructed.Invoke(
null,
new object[] { propertyExpression, entityParameter });
// Now we need to construct the Ignore method using the property's Type.
var ignoreMethod = config.GetType().GetMethod("Ignore");
var constructed = ignoreMethod.MakeGenericMethod(propertyInfo.PropertyType);
// Finally, we call the constructed Ignore method, using
// our expression as the argument.
constructed.Invoke(config, new object[] { expression });
}
return config;
}

Assign property of object by variable in C#.net [duplicate]

Is there a way in C# where I can use reflection to set an object property?
Ex:
MyObject obj = new MyObject();
obj.Name = "Value";
I want to set obj.Name with reflection. Something like:
Reflection.SetProperty(obj, "Name") = "Value";
Is there a way of doing this?
Yes, you can use Type.InvokeMember():
using System.Reflection;
MyObject obj = new MyObject();
obj.GetType().InvokeMember("Name",
BindingFlags.Instance | BindingFlags.Public | BindingFlags.SetProperty,
Type.DefaultBinder, obj, "Value");
This will throw an exception if obj doesn't have a property called Name, or it can't be set.
Another approach is to get the metadata for the property, and then set it. This will allow you to check for the existence of the property, and verify that it can be set:
using System.Reflection;
MyObject obj = new MyObject();
PropertyInfo prop = obj.GetType().GetProperty("Name", BindingFlags.Public | BindingFlags.Instance);
if(null != prop && prop.CanWrite)
{
prop.SetValue(obj, "Value", null);
}
You can also do:
Type type = target.GetType();
PropertyInfo prop = type.GetProperty("propertyName");
prop.SetValue (target, propertyValue, null);
where target is the object that will have its property set.
Reflection, basically, i.e.
myObject.GetType().GetProperty(property).SetValue(myObject, "Bob", null);
or there are libraries to help both in terms of convenience and performance; for example with FastMember:
var wrapped = ObjectAccessor.Create(obj);
wrapped[property] = "Bob";
(which also has the advantage of not needing to know in advance whether it is a field vs a property)
Or you could wrap Marc's one liner inside your own extension class:
public static class PropertyExtension{
public static void SetPropertyValue(this object obj, string propName, object value)
{
obj.GetType().GetProperty(propName).SetValue(obj, value, null);
}
}
and call it like this:
myObject.SetPropertyValue("myProperty", "myValue");
For good measure, let's add a method to get a property value:
public static object GetPropertyValue(this object obj, string propName)
{
return obj.GetType().GetProperty(propName).GetValue (obj, null);
}
Use somethings like this :
public static class PropertyExtension{
public static void SetPropertyValue(this object p_object, string p_propertyName, object value)
{
PropertyInfo property = p_object.GetType().GetProperty(p_propertyName);
property.SetValue(p_object, Convert.ChangeType(value, property.PropertyType), null);
}
}
or
public static class PropertyExtension{
public static void SetPropertyValue(this object p_object, string p_propertyName, object value)
{
PropertyInfo property = p_object.GetType().GetProperty(p_propertyName);
Type t = Nullable.GetUnderlyingType(property.PropertyType) ?? property.PropertyType;
object safeValue = (value == null) ? null : Convert.ChangeType(value, t);
property.SetValue(p_object, safeValue, null);
}
}
Yes, using System.Reflection:
using System.Reflection;
...
string prop = "name";
PropertyInfo pi = myObject.GetType().GetProperty(prop);
pi.SetValue(myObject, "Bob", null);
You can also access fields using a simillar manner:
var obj=new MyObject();
FieldInfo fi = obj.GetType().
GetField("Name", BindingFlags.NonPublic | BindingFlags.Instance);
fi.SetValue(obj,value)
With reflection everything can be an open book:) In my example we are binding to a private instance level field.
You can try this out when you want to mass-assign properties of an Object from another Object using Property names:
public static void Assign(this object destination, object source)
{
if (destination is IEnumerable && source is IEnumerable)
{
var dest_enumerator = (destination as IEnumerable).GetEnumerator();
var src_enumerator = (source as IEnumerable).GetEnumerator();
while (dest_enumerator.MoveNext() && src_enumerator.MoveNext())
dest_enumerator.Current.Assign(src_enumerator.Current);
}
else
{
var destProperties = destination.GetType().GetProperties();
foreach (var sourceProperty in source.GetType().GetProperties())
{
foreach (var destProperty in destProperties)
{
if (destProperty.Name == sourceProperty.Name && destProperty.PropertyType.IsAssignableFrom(sourceProperty.PropertyType))
{
destProperty.SetValue(destination, sourceProperty.GetValue(source, new object[] { }), new object[] { });
break;
}
}
}
}
I have just published a Nuget package that allows setting up not only the first level Properties but also nested properties in the given object in any depth.
Here is the package
Sets the value of a property of an object by its path from the root.
The object can be a complex object and the property can be multi level deep nested property or it can be a property directly under the root. ObjectWriter will find the property using the property path parameter and update its value. Property path is the appended names of the properties visited from root to the end node property which we want to set, delimited by the delimiter string parameter.
Usage:
For setting up the properties directly under the object root:
Ie. LineItem class has an int property called ItemId
LineItem lineItem = new LineItem();
ObjectWriter.Set(lineItem, "ItemId", 13, delimiter: null);
For setting up nested property multiple levels below the object root:
Ie. Invite class has a property called State, which has a property called Invite (of Invite type), which has a property called Recipient, which has a property called Id.
To make things even more complex, the State property is not a reference type, it is a struct.
Here is how you can set the Id property (to string value of “outlook”) at the bottom of the object tree in a single line.
Invite invite = new Invite();
ObjectWriter.Set(invite, "State_Invite_Recipient_Id", "outlook", delimiter: "_");
Based on MarcGravell's suggestion, I have constructed the following static method.The method generically assigns all matching properties from source object to target using FastMember
public static void DynamicPropertySet(object source, object target)
{
//SOURCE
var src_accessor = TypeAccessor.Create(source.GetType());
if (src_accessor == null)
{
throw new ApplicationException("Could not create accessor!");
}
var src_members = src_accessor.GetMembers();
if (src_members == null)
{
throw new ApplicationException("Could not fetch members!");
}
var src_class_members = src_members.Where(x => x.Type.IsClass && !x.Type.IsPrimitive);
var src_class_propNames = src_class_members.Select(x => x.Name);
var src_propNames = src_members.Except(src_class_members).Select(x => x.Name);
//TARGET
var trg_accessor = TypeAccessor.Create(target.GetType());
if (trg_accessor == null)
{
throw new ApplicationException("Could not create accessor!");
}
var trg_members = trg_accessor.GetMembers();
if (trg_members == null)
{
throw new ApplicationException("Could not create accessor!");
}
var trg_class_members = trg_members.Where(x => x.Type.IsClass && !x.Type.IsPrimitive);
var trg_class_propNames = trg_class_members.Select(x => x.Name);
var trg_propNames = trg_members.Except(trg_class_members).Select(x => x.Name);
var class_propNames = trg_class_propNames.Intersect(src_class_propNames);
var propNames = trg_propNames.Intersect(src_propNames);
foreach (var propName in propNames)
{
trg_accessor[target, propName] = src_accessor[source, propName];
}
foreach (var member in class_propNames)
{
var src = src_accessor[source, member];
var trg = trg_accessor[target, member];
if (src != null && trg != null)
{
DynamicPropertySet(src, trg);
}
}
}

Set object property using reflection

Is there a way in C# where I can use reflection to set an object property?
Ex:
MyObject obj = new MyObject();
obj.Name = "Value";
I want to set obj.Name with reflection. Something like:
Reflection.SetProperty(obj, "Name") = "Value";
Is there a way of doing this?
Yes, you can use Type.InvokeMember():
using System.Reflection;
MyObject obj = new MyObject();
obj.GetType().InvokeMember("Name",
BindingFlags.Instance | BindingFlags.Public | BindingFlags.SetProperty,
Type.DefaultBinder, obj, "Value");
This will throw an exception if obj doesn't have a property called Name, or it can't be set.
Another approach is to get the metadata for the property, and then set it. This will allow you to check for the existence of the property, and verify that it can be set:
using System.Reflection;
MyObject obj = new MyObject();
PropertyInfo prop = obj.GetType().GetProperty("Name", BindingFlags.Public | BindingFlags.Instance);
if(null != prop && prop.CanWrite)
{
prop.SetValue(obj, "Value", null);
}
You can also do:
Type type = target.GetType();
PropertyInfo prop = type.GetProperty("propertyName");
prop.SetValue (target, propertyValue, null);
where target is the object that will have its property set.
Reflection, basically, i.e.
myObject.GetType().GetProperty(property).SetValue(myObject, "Bob", null);
or there are libraries to help both in terms of convenience and performance; for example with FastMember:
var wrapped = ObjectAccessor.Create(obj);
wrapped[property] = "Bob";
(which also has the advantage of not needing to know in advance whether it is a field vs a property)
Or you could wrap Marc's one liner inside your own extension class:
public static class PropertyExtension{
public static void SetPropertyValue(this object obj, string propName, object value)
{
obj.GetType().GetProperty(propName).SetValue(obj, value, null);
}
}
and call it like this:
myObject.SetPropertyValue("myProperty", "myValue");
For good measure, let's add a method to get a property value:
public static object GetPropertyValue(this object obj, string propName)
{
return obj.GetType().GetProperty(propName).GetValue (obj, null);
}
Use somethings like this :
public static class PropertyExtension{
public static void SetPropertyValue(this object p_object, string p_propertyName, object value)
{
PropertyInfo property = p_object.GetType().GetProperty(p_propertyName);
property.SetValue(p_object, Convert.ChangeType(value, property.PropertyType), null);
}
}
or
public static class PropertyExtension{
public static void SetPropertyValue(this object p_object, string p_propertyName, object value)
{
PropertyInfo property = p_object.GetType().GetProperty(p_propertyName);
Type t = Nullable.GetUnderlyingType(property.PropertyType) ?? property.PropertyType;
object safeValue = (value == null) ? null : Convert.ChangeType(value, t);
property.SetValue(p_object, safeValue, null);
}
}
Yes, using System.Reflection:
using System.Reflection;
...
string prop = "name";
PropertyInfo pi = myObject.GetType().GetProperty(prop);
pi.SetValue(myObject, "Bob", null);
You can also access fields using a simillar manner:
var obj=new MyObject();
FieldInfo fi = obj.GetType().
GetField("Name", BindingFlags.NonPublic | BindingFlags.Instance);
fi.SetValue(obj,value)
With reflection everything can be an open book:) In my example we are binding to a private instance level field.
You can try this out when you want to mass-assign properties of an Object from another Object using Property names:
public static void Assign(this object destination, object source)
{
if (destination is IEnumerable && source is IEnumerable)
{
var dest_enumerator = (destination as IEnumerable).GetEnumerator();
var src_enumerator = (source as IEnumerable).GetEnumerator();
while (dest_enumerator.MoveNext() && src_enumerator.MoveNext())
dest_enumerator.Current.Assign(src_enumerator.Current);
}
else
{
var destProperties = destination.GetType().GetProperties();
foreach (var sourceProperty in source.GetType().GetProperties())
{
foreach (var destProperty in destProperties)
{
if (destProperty.Name == sourceProperty.Name && destProperty.PropertyType.IsAssignableFrom(sourceProperty.PropertyType))
{
destProperty.SetValue(destination, sourceProperty.GetValue(source, new object[] { }), new object[] { });
break;
}
}
}
}
I have just published a Nuget package that allows setting up not only the first level Properties but also nested properties in the given object in any depth.
Here is the package
Sets the value of a property of an object by its path from the root.
The object can be a complex object and the property can be multi level deep nested property or it can be a property directly under the root. ObjectWriter will find the property using the property path parameter and update its value. Property path is the appended names of the properties visited from root to the end node property which we want to set, delimited by the delimiter string parameter.
Usage:
For setting up the properties directly under the object root:
Ie. LineItem class has an int property called ItemId
LineItem lineItem = new LineItem();
ObjectWriter.Set(lineItem, "ItemId", 13, delimiter: null);
For setting up nested property multiple levels below the object root:
Ie. Invite class has a property called State, which has a property called Invite (of Invite type), which has a property called Recipient, which has a property called Id.
To make things even more complex, the State property is not a reference type, it is a struct.
Here is how you can set the Id property (to string value of “outlook”) at the bottom of the object tree in a single line.
Invite invite = new Invite();
ObjectWriter.Set(invite, "State_Invite_Recipient_Id", "outlook", delimiter: "_");
Based on MarcGravell's suggestion, I have constructed the following static method.The method generically assigns all matching properties from source object to target using FastMember
public static void DynamicPropertySet(object source, object target)
{
//SOURCE
var src_accessor = TypeAccessor.Create(source.GetType());
if (src_accessor == null)
{
throw new ApplicationException("Could not create accessor!");
}
var src_members = src_accessor.GetMembers();
if (src_members == null)
{
throw new ApplicationException("Could not fetch members!");
}
var src_class_members = src_members.Where(x => x.Type.IsClass && !x.Type.IsPrimitive);
var src_class_propNames = src_class_members.Select(x => x.Name);
var src_propNames = src_members.Except(src_class_members).Select(x => x.Name);
//TARGET
var trg_accessor = TypeAccessor.Create(target.GetType());
if (trg_accessor == null)
{
throw new ApplicationException("Could not create accessor!");
}
var trg_members = trg_accessor.GetMembers();
if (trg_members == null)
{
throw new ApplicationException("Could not create accessor!");
}
var trg_class_members = trg_members.Where(x => x.Type.IsClass && !x.Type.IsPrimitive);
var trg_class_propNames = trg_class_members.Select(x => x.Name);
var trg_propNames = trg_members.Except(trg_class_members).Select(x => x.Name);
var class_propNames = trg_class_propNames.Intersect(src_class_propNames);
var propNames = trg_propNames.Intersect(src_propNames);
foreach (var propName in propNames)
{
trg_accessor[target, propName] = src_accessor[source, propName];
}
foreach (var member in class_propNames)
{
var src = src_accessor[source, member];
var trg = trg_accessor[target, member];
if (src != null && trg != null)
{
DynamicPropertySet(src, trg);
}
}
}

Categories

Resources