Get Leaf Property Value Out Of Object's Tree Graph - c#

I am stuck with PropertyInfo, big time. Basically it a tiny issue though idk where to start solving it. I dont usually use reflection but I need it now.
I have an object which has a property of type MyClass and MyClass futhermore holds another property. I want that last one. How do I get it?
Take a look at this:
obj.myClass.Attribute
How do I get that Attribute property by using PropertyInfo?

Use PropertyInfo.GetValue(Object):
Type type = obj.myClass.GetType();
PropertyInfo prop = type.GetProperty("Attribute");
object value = prop.GetValue(obj.myClass);

Related

How to browse object hierarchy in C#

I went to an interview recently and there they asked me the following question:
Write a component to travel through an object hierarchy based on the data path passed in and return the value of the property implemeting the following method:
Public object getValueFromPath(object parentObj, string dataPath);
The object hierarchy will be some thing like this:
Object1
objectRef2
property1
property2
parentObj will be Object1
dataPath will be objectRef2.property2
Can some one give me an idea how I can do that.
You would need to use reflection.
First step would be to split the dataPath on ., and get a reference to the System.Type object representing the type of parentObj (parentObj.GetType()).
Then for each element in the path you would use something like .GetMember(...) on the Type object to find the member with that name, and update the current Type object accordingly.
Once you get to the property at the end, and you have the associated ProprtyInfo object, you then need to call .GetValue(...) to get the value of the property.

Access all properties of an unknown type

On my WinForm, I want to show each Property (as a label) and its value at run time depending on the type of the object. Something like this:
public void ShowDetails(object anyType)
{
// Generate label per property and show value of the property against a label.
}
How can I achieve this? There are more than 100 classes having different properties.
I am using C# 4.0.
You use reflection.
PropertyInfo[] properties = obj.GetType().GetProperties();
foreach (PropertyInfo property in properties)
{
object propertyValue = property.GetValue(obj, null);
}
That should be enough to get you started.
You can also get lots of other information out of the PropertyInfo such as the name of the property, the type, the accessibility, and so on. Note that it's possible (but very uncommon) to have a property without a getter, so you may want to check for that first. You also may want to only get public properties, rather than all properties. You also may want to check if the property is an indexer, as it will need a non-null value for the second parameter of GetValue. Oh, and you will also get static properties returned; you may or may not want those as well.
Use System.Reflection.PropertyInfo . You can loop through all properties (and sub-properties)
MSDN link
You can easily store the properties and their values in a dictionary
Dictionary<string,object> properties = anyType.GetType()
.GetProperties()
.ToDictionary(p=>p.Name,p=>p.GetValue(anyType,null));
I'd read up on Reflection. It will allow you to access the property names and values of class member at runtime.

How to set a value when the name of the value isn't known until runtime?

I am trying to set the properties of one object to be the same as the properties of another object. Here the code so far:
private T SetObjectAttributes<T> (dynamic fromO, T toO)
{
foreach (var prop in fromO.GetType().GetProperties())
{
toO[prop] = fromO[prop];
}
return toO;
}
The syntax here is incorrect:
toDbObject[prop] = fromObject[prop];
Basically, I am trying to set a property but the property name isn't known until run time. So my question is how to assign the value of the property at runtime.
You have to use the methods GetValue( object sourceObject) respectively SetValue( object target, object value ) of the PropertyInfo instance of the property.
You want to use PropertyInfo.SetValue to actually set the value. Also I hope you're caching those PropertyInfo instances - because it's going to really slow otherwise.
You should also look at ExpandoObject or some other options.
What exactly are you trying to do? Perhaps there's an altogether better way.

Set Reflection Property object without knowing the property name & value

I have a class named BackUp that contains a few properties.
Let's say I have an existing instance of BackUp with its properties initialized.
As I use reflection in the BackUp class where I want to create an AgentActivator object and I need to set its properties, the idea is to retrieve the properties from the BackUp object.
The problem is to take PropertyInfo object from the BackUp object and set the matching property on the reflected object.
I am doing the following:
Assembly assembly = Assembly.LoadFile(localBackUp.AssemblyFileName);
Type currentClasstype = assembly.GetType(localBackUp.ClassName);
PropertyInfo[] properties = currentClasstype.GetProperties();
object classInstance = Activator.CreateInstance(localBackUp.AssemblyFileName,
localBackUp.ClassName);
string propName= null;
foreach(PropertyInfo prop in properties)
{
propName= prop.Name;
currentClasstype.GetProperty(propName).
SetValue(classInstance, findProperty(localBackUp, propNmae), null);
}
I need to find a way to implement the findProperty Method.
Its job is to get the string (property name) and return the matching value from the localBackUp which holds property with the propName.
From your code I assume that Type of localBackup and classInstance is the same and thus are just initializing a new class instance with the same property values another class instance (localBackup) already has try
prop.GetSetMethod().Invoke (classInstance, new object[] { prop.GetGetMethod().Invoke(localBackUp, null) } );
One remark though:
IF my assumption is true then there are IMHO much better options to do what you are trying (for example by serializing and deserializing an instance)...
If your goal is clone the object, the best (I think) approach is described here: Deep cloning objects (as #Yahia mentioned serialize and deserialize). Quite important is that it returns deep copy, so original and new object don't share data between itself.

Property Name and need its value

I have a name of a property and need to find its value within a Class, what is the fastest way of getting to this value?
I am making the assumption that you have the name of the property in runtime; not while coding...
Let's assume your class is called TheClass and it has a property called TheProperty:
object GetThePropertyValue(object instance)
{
Type type = instance.GetType();
PropertyInfo propertyInfo = type.GetProperty("TheProperty");
return propertyInfo.GetValue(instance, null);
}
I assume you mean you have the name of the property as a string. In this case, you need to use a bit of reflection to fetch the property value. In the example below the object containing the property is called obj.
var prop = obj.GetType().GetProperty("PropertyName");
var propValue = prop.GetValue(obj, null);
Hope that helps.
If you're interested in speed at runtime rather than development, have a look at Jon Skeet's Making reflection fly and exploring delegates blog post.
Just use the name of the property. If it is a nullable property (e.g. int ? property) use property.Value.
At runtime you can use reflection to get the value of the property.
Two caveats:
Obfuscation: An obfuscator may change
the name of the property, which
will break this functionality.
Refactoring: Using reflection in this
manner makes the code more difficult
to refactor. If you change the name
of the property, you may have to
search for instances where you use
reflection to get the property value
based upon name.

Categories