mattlarsen0
mattlarsen0

Reputation: 123

Determine if a class member's type was defined as a generic parameter

Given a generic class:

public class Foo<T>
{
    public T Data { get; set; }
    public string Bar { get; set; }
}

Declared as:

var someVar = new Foo<string>();

Is there any way to tell if the type of Data is defined as a generic T and not string?

I know you can check if the type of Data is a string, but I want to determine if a member is defined by a generic parameter.

I am not trying to determine if Data is a string. I am trying to check if Data was defined by T. I do not think this is possible.

Upvotes: 1

Views: 134

Answers (1)

Lasse V. Karlsen
Lasse V. Karlsen

Reputation: 391276

You have to go through the generic type definition, in which the properties using the generic type parameters will still be open:

void Main()
{
    Test(typeof(Foo<string>), "Data");
    Test(typeof(Foo<string>), "Bar");
}

public void Test(Type type, string propertyName)
{
    if (type.IsGenericType)
        type = type.GetGenericTypeDefinition();

    PropertyInfo pi = type.GetProperty(propertyName);
    if (pi.PropertyType.IsGenericTypeParameter)
        Console.WriteLine("<generic> " + pi);
    else
        Console.WriteLine("<not generic> " + pi);
}

public class Foo<T>
{
    public T Data { get; set; }
    public string Bar { get; set; }
}

Output:

<generic> T Data
<not generic> System.String Bar

Upvotes: 2

Related Questions