Simple question:
If you have a string x, to initialize it you simple do one of the following:
string x = String.Empty;
or
string x = null;
What about Generic parameter T?
I’ve tried doing:
void someMethod<T>(T y)
{
T x = new T();
...
}
Generate error :
Cannot create an instance of the variable type ‘T’ because it does not have the new() constraint
You have two options:
You can constrain T: you do this by adding:
where T : new()to your method. Now you can only use thesomeMethodwith a type that has a parameterless, default constructor (see Constraints on Type Parameters).Or you use
default(T). For a reference type, this will givenull. But for example, for an integer value this will give0(see default Keyword in Generic Code).Here is a basic console application that demonstrates the difference:
It produces the following output: