Generics in C# - how can I create an instance of a variable type with an argument?

C#Generics

C# Problem Overview


I've got a generics class, where I want to instantiate an object with the generic type. I want to use an argument for the constructor of the type.

My code:

public class GenericClass<T> where T : Some_Base_Class, new()
{
    public static T SomeFunction(string s)
    {
        if (String.IsNullOrEmpty(s))
            return new T(some_param);
    }
}

I get an error on the

new T(some_param)

> 'T': cannot provide arguments when creating an instance of a variable > type

Any ideas how can I do this?

C# Solutions


Solution 1 - C#

Take a look at Activator.CreateInstance. For instance:

var instance = Activator.CreateInstance(typeof(T), new object[] { null, null });

Obviously replacing the nulls with appropriate values expected by one of the constructors of the type.

If you receive a compiler error about cannot convert object to type T, then include as T:

var instance = Activator.CreateInstance(typeof(T), 
                  new object[] { null, null }) as T;

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRomanView Question on Stackoverflow
Solution 1 - C#Grant ThomasView Answer on Stackoverflow