Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

generics

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?

like image 901
Roman Avatar asked Jun 20 '11 11:06

Roman


People also ask

What are generics and templates?

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.

Why generics are used in C#?

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.

What is a generic class in C#?

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.

What is the meaning of generics in programming?

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.


1 Answers

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; 
like image 65
Grant Thomas Avatar answered Oct 13 '22 06:10

Grant Thomas