I have something like this
V Func<V>()
{
// do stuff
V res = default(V);
// more stuff
return res;
}
The problem is that I want res to be either 0 or a new instance of V
I tried creating 2 methods
Func<V> where T: new()
Func<V> where T: struct
but surprisingly this is not allowed
My workaround is to have 2 functions
FuncNew<V> where T: new()
...
res = new V();
....
and
FuncDefault<V> where T: struct
...
res = default(V)
...
EDIT: Summarize answers
new(T) will new up a ref or value type; I did not realize that
You can use the
new()constraint:Value types will be initialized to all-zeros, and any reference types will be initialized using their no-args default constructor.
If the reference type doesn’t have a no-args constructor it can’t be used with this method, and you’ll have to use other ways (there are plenty of solutions to this problem elsewhere on SO, eg Passing arguments to C# generic new() of templated type)