In C#, How to Instantiate a Passed Generic Type Inside a Method

In C#, how to instantiate a passed generic type inside a method?

Declare your method like this:

public string InstantiateType<T>(string firstName, string lastName) 
where T : IPerson, new()

Notice the additional constraint at the end. Then create a new instance in the method body:

T obj = new T();    

Instantiate Generic Type in C# class

If you want to create your own instance of T, then you need define a constraint new()

class Data<T> where T: new()
{
T obj;

public Data()
{
obj = new T();
}
}

If you want to pass in the obj then you need to allow it in the constructor

 class Data<T>
{
T obj;

public Data(T val)
{
obj = val;
}
}

How to create instance of a generic type passed to the service method?

You need the new constraint

The new constraint specifies that any type argument in a generic class
declaration must have a public parameterless constructor. To use the
new constraint, the type cannot be abstract.

public Task<T> ScrapGenericObject<T>(int id, string jobType) where T : new()
{
var someObject = new T();
return someObject;
}

If you need to pass in any constructors you will have to use a different approach Activator.CreateInstance

Creates an instance of the specified type using the constructor that
best matches the specified parameters.

 return (T)Activator.CreateInstance(typeof(T), new object[] { param1, param2 });

How to instantiate a generic type in base class?

If it has a default constructor, add the New Constraint, and new it up

The new constraint specifies that a type argument in a generic class
declaration must have a public parameterless constructor. To use the
new constraint, the type cannot be abstract.

Example

public abstract class XmlParser<TProduct> 
where TProduct : ProductBase, new()

...

public List<TProduct>Parse()
{
var product = new TProduct();

...

Instantiate an instance of a generic type in C#

It seems like List<T> already has all you need except a method to create a new instance and add it, which could be added as extension methods:

public static ICollectionExtensions
{
public static AddNew<T>(this ICollection<T> collection)
where T : new()
{
var newItem = new T();
collection.Add(newItem);
}

...
}

which can be used like this:

var list = new List<int>();
list.AddNew();

Create instance of class with generic type and call method of same generic type from string name of object at runtime

Your wrapper got the following signature:

public class MyClass<T> where T : class, new()

it basically says "T needs to be a class and have a default constructor". The interesting part is about the default constructor. It means that the class must have a constructor with no arguments.

It tells .NET that you can invoke:

var obj = new T();

So the first step is to do just that:

public class MyClass<T> where T : class, new()
{
public IList<T> MyMethod(Stream stream)
{
var data = new List<T>();

//this
var obj = new T();

return data;
}
}

next you wanted to invoke a method. That's done with the help of reflection.

A simple example is:

var obj = new T();

//get type information
var type = obj.GetType();

//find a public method named "DoStuff"
var method = type.GetMethod("DoStuff");

// It got one argument which is a string.
// .. so invoke instance **obj** with a string argument
method.Invoke(obj, new object[]{"a string argument"});

Update

I missed the important part:

I need to return my IList from the MyMethod() method based on the name of the object I'm passing in as a string.

If the type is declared in the same assembly as your executing code you can just pass the full type name like Some.Namespace.ClassName" toType.GetType()`:

var type = Type.GetType("Some.Namespace.ClassName");
var obj = Activator.CreateInstance(type);

If the class is declared in another assembly you need to specify it:

var type = Type.GetType("Some.Namespace.ClassName, SomeAsseblyName");
var obj = Activator.CreateInstance(type);

The rest is pretty much the same.

If you only have the class name you can traverse the assembly to find the correct type:

var type = Assembly.GetExecutingAssembly()
.GetTypes()
.FirstOrDefault(x => x.Name == "YourName");
var obj = Activator.CreateInstance(type);

How to generically instantiate a generic class in C#?

You can't type the list as generic, since you don't know the type parameter, but you can create a List instance at runtime.

Type t = Program.CheckType(someInput);
Type listType = typeof(List<>).MakeGenericType(t);
IList list = (IList) Activator.CreateInstance(listType);

If you try to add an object of the incorrect type, you will get an exception, so this approach has an advantage over using a collection like ArrayList, or List<object>



Related Topics



Leave a reply



Submit