czubehead
czubehead

Reputation: 552

C# get generic parameter name using reflection

say that I have a C# class like this:

class MyClass<Tkey,Tvalue>{}

How do I get "Tkey" and "Tvalue" from given Type instance? I need the parameter name, not Type.

EDIT My class is of unknown type, so it can be something like

class MyClass2<Ttype>{}

as well

Upvotes: 2

Views: 2785

Answers (2)

Domysee
Domysee

Reputation: 12854

You can use Type.GetGenericArguments to get the Types. From them you can select the name:

IEnumerable<string> genericParameterNames = instance.GetType().GetGenericArguments().Select(t => t.Name);

Edit:

To get the names of the generic arguments, you should have a look at NineBerry's answer. A simplified version of it is this:

IEnumerable<string> genericParameterNames = instance.GetType()
    .GetGenericTypeDefinition()
    .GetGenericArguments()
    .Select(t => t.Name)

Upvotes: 1

NineBerry
NineBerry

Reputation: 28559

You first have to use the method GetGenericTypeDefinition() on the Type to get another Type that represents the generic template. Then you can use GetGenericArguments() on that to receive the definition of the original placeholders including their names.

For example:

    class MyClass<Tkey, Tvalue> { };


    private IEnumerable<string> GetTypeParameterNames(Type fType)
    {
        List<string> result = new List<string>();

        if(fType.IsGenericType)
        {
            var lGenericTypeDefinition = fType.GetGenericTypeDefinition();

            foreach(var lGenericArgument in lGenericTypeDefinition.GetGenericArguments())
            {
                result.Add(lGenericArgument.Name);
            }
        }

        return result;
    }

    private void AnalyseObject(object Object)
    {
        if (Object != null)
        {
            var lTypeParameterNames = GetTypeParameterNames(Object.GetType());
            foreach (var name in lTypeParameterNames)
            {
                textBox1.AppendText(name + Environment.NewLine);
            }
        }
    }

    private void button1_Click(object sender, EventArgs e)
    {
        var object1 = new MyClass<string, string>();
        AnalyseObject(object1);

        var object2 = new List<string>();
        AnalyseObject(object2);

        AnalyseObject("SomeString");
    }

Upvotes: 2

Related Questions