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?
Generics are generic until the types are substituted for them at runtime. Templates are specialized at compile time so they are not still parameterized types at runtime. The common language runtime specifically supports generics in MSIL.
Generics allow you to define the specification of the data type of programming elements in a class or a method, until it is actually used in the program. In other words, generics allow you to write a class or method that can work with any data type.
Generic is a class which allows the user to define classes and methods with the placeholder. Generics were added to version 2.0 of the C# language. The basic idea behind using Generic is to allow type (Integer, String, … etc and user-defined types) to be a parameter to methods, classes, and interfaces.
Generic programming is a style of computer programming in which algorithms are written in terms of types to-be-specified-later that are then instantiated when needed for specific types provided as parameters.
Take a look at Activator.CreateInstance
. For instance:
var instance = Activator.CreateInstance(typeof(T), new object[] { null, null });
Obviously replacing the null
s 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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With