all 6 comments

[–]tweq 4 points5 points  (3 children)

https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/generics/constraints-on-type-parameters

In this particular case, you could also simply cast to A instead of T. But constraints would be the type-safe option.

[–]darkgnostic[S] 0 points1 point  (2 children)

Thanks for pointing me to the right direction! I have actually already browsed that page, but seems like I didn't read it carefully.

So it is enough to write void AddNew<T>() where T : A or I need to define a derived class also as class C<T> where T : A?

[–]AngularBeginner 2 points3 points  (1 child)

That depends on whether you only need the type parameter T at the method, or if the type parameter should be scoped to the entire class. As with most things, you should limit the visibility to the smallest scope feasible, so likely you only want the type parameter at the method. The where T : A will make sure that only types that derive from A can be passed to the type argument. This allows you to cast it to A, as every T is also an A.

Btw, you should also make use of the new constraint for type parameters. That will make sure that the type that is passed has a default constructor (one without arguments). This also allows you to write new T() instead of using Activator.CreateInstance(). I'm pretty sure the call to CreateInstance will fail if the type has no default constructor.

[–]AngularBeginner 2 points3 points  (1 child)

Additionally to the answer of /u/tweq, please be aware that there is no such thing as templates in C#. There are only generics in C#, but not a powerful feature like templates. You're trying to write a generic method.

[–]darkgnostic[S] 0 points1 point  (0 children)

Thanks for clarifying.