Arash
Arash

Reputation: 4260

How to obtain the object type of another object's property in C#?

Let's suppose we have the following two classes' definitions:

public class ParentClass
{
   public ChildClass[] Children{ get; set; }
}

public class ChildClass
{
   public int Id{ get; set; }
}

We can iterate through the properties of ParentClass using System.Type but I could not find a way in dotnet core to determine the non-array type of Children which is ChildClass. For example, I'd like to have a test like the following one always to pass:

Type childType = GetChildTypeOf(typeof(ParentClass));
Assert.True(childType == typeof(ChildClass));

In that case, how should GetChildTypeOf(...) be implemented?

Upvotes: 0

Views: 88

Answers (1)

G.Dimov
G.Dimov

Reputation: 2393

Considering there could be more than one property, the GetChildTypeOf better return List<Type> objects.

private static List<Type> GetChildTypeOf(Type parent)
{
    var res = new List<Type>();

    var props = parent.GetProperties();
    foreach (var prop in props)
    {
        var propType = prop.PropertyType;
        var elementType = propType.GetElementType();
        res.Add(elementType);
    }

    return res;
}

Then you make your assertion:

var childType = GetChildTypeOf(typeof(ParentClass));
Assert.True(childType.First() == typeof(ChildClass));

Probably it would be even better to have one method to return them all, and one to return a child type element by given property name.

Edit: Here is how it should look for a specific property name:

private static Type GetSpecificChildTypeOf(Type parent, string propertyName)
{
    var propType = typeof(ParentClass).GetProperty(propertyName).PropertyType;
    var elementType = propType.GetElementType();

    return elementType;
}

And use it like this:

var childType = GetSpecificChildTypeOf(typeof(ParentClass), "Children");
Assert.True(childType == typeof(ChildClass))

Edit: Thanks for marking the answer!

Upvotes: 2

Related Questions