Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use the "where" keyword in C# with a generic interface, and inheritance

Tags:

c#

.net

What I want to achieve is this:

  • Declare a generic class (<T>),
  • Have the "T" restricted to types that implement IMySpecialInterface<X> (where "X" is not a known type),
  • And have the class inherit from a parent class.

to give an incorrect example:

public class MyClass<T> : MyParentClass where T : IMySpecialInterface<X>
{
...
}

What is the proper syntax to achieve this?

Thanks.

like image 661
Sako73 Avatar asked Aug 05 '10 21:08

Sako73


People also ask

Can you use this keyword in C?

In C you do not have the this keyword. Only in C++ and in a class, so your code is C and you use your this variable as a local method parameter, where you access the array struct.

What is the this keyword in C?

In C++ programming, this is a keyword that refers to the current instance of the class. There can be 3 main usage of this keyword in C++. It can be used to pass current object as a parameter to another method. It can be used to refer current class instance variable.

Is there Auto type in C?

Auto is a storage class/ keyword in C Programming language which is used to declare a local variable. A local variable is a variable which is accessed only within a function, memory is allocated to the variable automatically on entering the function and is freed on leaving the function.


1 Answers

You can't use generics without knowing the types, unless you created the type at runtime.

Your best fit would be:

public class MyClass<T, U> : MyParentClass where T: IMySpecialInterface<U>
{

}

UPDATE or could you potentially use dynamic?

like image 111
Matthew Abbott Avatar answered Sep 30 '22 18:09

Matthew Abbott