David DB
asked on
Restictions on T
Hi
Is the only way to have restrictions on T to make an interface, or are there any other way ?
Since "where T:" can have only one class:
Is the only way to have restrictions on T to make an interface, or are there any other way ?
Since "where T:" can have only one class:
public object Test<T>(int whatType) where T:testclass
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Consider the following -
Open in new window
Implementations -Open in new window
If I call the GetName method with a new Person instance I will get a name, but I will not be able to call the GetName method using new instances of an Employee or Dog because it is constrained to only classes which are of type Person, implement the ISomeNamer interface and have a default parameterless constructor.Proof of concept -
Open in new window
Give the following errors:You would think to fix this that you would simply add the Employee type to the where clause, but you cannot do that, instead what you would have to do is make the Employee class a child of the Person class; e.g -Open in new window
Now the instance of the Employee class can call the GetName method.-saige-