How create a generic method that can initialize value variable to 0 or ref variable to new (not null)?

You can use the new() constraint: private V Func() where V : new() { // do stuff V res = new V(); // more stuff return res; } 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 C# Generic new() constructor problem ).

You can use the new() constraint: private V Func() where V : new() { // do stuff V res = new V(); // more stuff return res; } 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 C# Generic new() constructor problem).

1 And note that for any struct (including Nullable), new T() is equivalent to default(T). – Jon Skeet May 18 at 20:27 this doesn't work for value types – pm100 May 18 at 20:48 return V; is a little fishy :) – Marino Å imić May 18 at 20:49 Indeed; I should have looked closer at his method :) – thecoop May 18 at 20:54 1 @pm100: yes it does, I've just tried it. Unless you want to do something other than return all-zeros for value types?

– thecoop May 18 at 20:56.

That's not possible because the generic type parameter would only be valid for the integer type unless you specify object as the return type. Public object Func() where T: new() { if(something) return 0; return new T(); } If you're trying to make a default initializer, you just need to new up the type. This should work for both integer and reference types.

Public T Func() { return Activator.CreateInstance(); }.

Generally, it's better to use new T() rather than Activator. CreateInstance directly, as the C# compiler inserts some optimizations to make it very fast for value types. – thecoop May 18 at 20:37 Indeed.

After looking at your implementation, new() is more concise. – Tejs May 18 at 20:38 the 'something' I would need to test is whether V is ref or value type – pm100 May 18 at 20:49 if(typeof(T). IsSubclassOf(typeof(ValueType))) should do the trick.

– Tejs May 180 at 13:21.

I cant really gove you an answer,but what I can give you is a way to a solution, that is you have to find the anglde that you relate to or peaks your interest. A good paper is one that people get drawn into because it reaches them ln some way.As for me WW11 to me, I think of the holocaust and the effect it had on the survivors, their families and those who stood by and did nothing until it was too late.

Related Questions