If one wants to create a new instance of a generic, the new constraint needs to be defined, like so:
public T SomeMethod<T>() where T : new()
{
return new T();
}
Is it possible, using reflection, to create an instance of T without the new constraint, like so (contains pseudocode):
public T SomeMethod<T>()
{
if (T has a default constructor)
{
return a new instance of T;
}
else
{
return Factory<T>.CreateNew();
}
}
The new constraint specifies that a type argument in a generic class or method declaration must have a public parameterless constructor. To use the new constraint, the type cannot be abstract.
2. What is the function of the not null constraint? Explanation: The not null constraint ensures that data is entered into the database. It displays an error message whenever a data field mentioned is left empty.
You can create your own generic classes, methods, interfaces and delegates. You can create generic collection classes. The . NET framework class library contains many new generic collection classes in System.
Use Activator.CreateInstance()
for this. See http://msdn.microsoft.com/en-us/library/system.activator.createinstance.aspx for more information on how to use this method. Basically, what you do is:
var obj = (T)Activator.CreateInstance(typeof(T));
You can verify whether it has a default constructor by using the GetConstructors()
method:
var constructors = typeof(T).GetConstructors();
If you find a constructor that has zero parameters, you can use the Activator.CreateInstance
method. Otherwise, you use the Factory<T>.CreateNew()
method.
EDIT:
To find out directly whether a constructor without any parameters exist, you can use the following check:
if (typeof(T).GetConstructor(Type.EmptyTypes) != null)
{
// ...
Generic methods with a where T : new()
constraint implement new T()
calls by invoking Activator.CreateInstance<T>()
. One interesting thing about this method is that it doesn't include the constraint, so if you are happy to defer the check until runtime, just use:
public T SomeMethod<T>() {
return Activator.CreateInstance<T>();
}
which will either do exactly what return new T()
would have done, or will raise a meaningful exception. Because it handles both the success and failure case, there is no real benefit in doing any additional checks, unless you wanted to do something obscure like not using a constructor at all (which can be done).
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