Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 651
czubehead Avatar asked Jun 08 '26 18:06

czubehead


1 Answers

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");
    }
like image 130
NineBerry Avatar answered Jun 10 '26 06:06

NineBerry



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!