c# - Generics new keyword with inheritance -


i need only allow types inherited person class used method. valid way of doing this?

public static void add<t>(t item) t : person, new() {} 

the person constraint satisfies condition object of type person (or 1 of it's subclasses) can used method. constructor constraint (new) ensures provided type has public, parameterless constructor. necessary when method invokes constructor on class.

for example:

public static void add<t>(t item) t : person, new() {     var newitem = new t();     ... } 

here new constraint needed because of line new t(). if method doesn't contain call constructor that, not need include new constraint.

if wanted ensure objects types subclasses of person can used method , not objects of type person, either make person abstract or make sure not have public, parameterless constructor (subclasses have provide 1 in order used method).

further reading


Comments

Popular posts from this blog

java - Jmockit String final length method mocking Issue -

asp.net - Razor Page Hosted on IIS 6 Fails Every Morning -

c++ - wxwidget compiling on windows command prompt -