Instantiation of C# generics
Method One
Add a where T: new()
after a class that uses generics
public class Example<T> where T : new()
{
public static T Get()
{
T t = new T();
...........
}
}
Method Two
You can use System.Activator.CreateInstance<T>()
to create generic instance pairs
public class Example<T>
{
public static T Get()
{
T t = System.Activator.CreateInstance<T>();
.....
}
}
- Link : https://www.zdyla.com/en/post/csharp-generic-create-instance.html
- Copyright Notice : Unless otherwise stated, please contact the author for authorization and indicate the source!