Reputation: 2783
I have an object from a class (let's call it classA
), and I know that it has a property object from another class (classB
). How can I find the object with type classB
and return it (with all it's values)?
//classA:
int id;
string name;
classB subItem;
//classB:
int randomNumber;
string answerOfLife;
I wrote this function that search all the properties of classA
for the one with propertyType classB
. I can find the property, but then I'm stuck with a PropertyInfo
object, where I really want a classB
object with all the values.
classB tempObject = (classB) classAObject.FindPropertyType("classB");
Function:
internal BaseDataObject FindPropertyType(string strMember) {
foreach (PropertyInfo prop in this.GetType().GetProperties())
{
if (prop.PropertyType.Name.ToString().ToLower() == strMember.ToLower())
//This is where it goes wrong!
return (BaseDataObject) prop.GetValue(this,null);
}
return null;
}
the prop.GetValue(this,null)
returns the parent (classA
) object instead of the desired classB
object.
Upvotes: 1
Views: 84
Reputation: 2403
I've updated my answer to use generics, see my previous use of is
and as
below which was upvoted before:
Use Generics. It will make this logic much more flexible and reusable:
We need to replace all calls to BaseDataObject
to T
in your internal method, so I modified FindPropertyByType:
public class BaseDataObject
{
internal T FindPropertyType<T>(string strMember)
{
var type = this.GetType();
var props = type.GetProperties();
foreach (PropertyInfo prop in props)
{
if (prop.PropertyType.Name.ToString().ToLower() == strMember.ToLower())
//This is where it goes wrong!
return (T)prop.GetValue(this, null);
}
return default(T);
}
}
The default(T)
will return the default value for the type of T, which in your case is Null.
Now, whenever you need this method you can specify which type you want, like so:
B tempObject = a.FindPropertyType<B>("B");
additionally, this should work too:
var myId = a.FindPropertyType<int>("id");
Previous Answer Below
If I read your question correctly you can use the is
keyword (MSDN Doc)
if( someProperty is classB)
//do something
else
//do something different
or you can use as
keyword(MSDN doc) which will return null if the object is the one you are casting:
private classB getPropAsClassB(someProperty)
{
return someProperty as classB;
}
var myProp = getPropAsClassB(someProp); //will be null if it isn't a classB object
Upvotes: 3
Reputation: 13676
Let's say you have list of objects :
List<object> objects; // all types of objects here include classA, int, string etc
Then you can do :
classB tempObject = (objects.FirstOrDefault(o => o is classA) as ClassA).subItem;
If objects doesn't contain any instances of ClassA this will throw Nullreference exception when we try to access the 'subItem' property...
Upvotes: 1