Search code examples
c#if-statementgenericstypes

Initialize an generic object in if-else statement


I need to create a generic object with type that depend on user choice. I get it from radio buttons. Here is an idea that I imagine:

        Class<null> object;

        if (radioInteger.Checked == true)
        {
            object = new Class<int>();
        }
        if (radioFloat.Checked == true)
        {
            object list = new Class<float>();
        }
        if (radioString.Checked == true)
        {
            object list = new Class<String>();
        }

        //do smth with object

How can I do it with C#?

I have tried to put type in variable and then put it between <>, but compiler says that I put variable instead of type.


Solution

  • If the type is not known at compile-time then you have to construct your object using the type object/instance and not a type argument/generic. Look into the non-generic overloads of Activator.CreateInstance.

    Note that it is better if you can know the type at compile-time since then you could for example constrain it to types that have a default constructor. Otherwise, using the non-generic Activator.CreateInstance call, you may get an exception if there is no suitable constructor to call. This all depends on your particular design though.