Forcing Generic Types....

M

MMAS

Hey Everyone

I know that I can do something like this in C#
MyClass<WHATEVER>
{
private WHATEVER var_name_of_type_whatever;
public ChangeVar(WHATEVER change_to_value)
{
var_name_of_type_whatever = change_to_value;
}
}

But is there a way to do this?

MyClass<WHATEVER:RealInterfaceClass>
{
private WHATEVER
var_name_of_type_whatever_that_is_forced_to_be_of_basetype_RealInterfaceClass;
public CallMethodThatExistsOnRealInterfaceClass()
{

var_name_of_type_whatever_that_is_forced_to_be_of_basetype_RealInterfaceClass.MethodIKnowExists();
}
}

so that in my templated code I can treat that variable as a
RealInterfaceClass and call its methods?

I'm just curious if something like this is possible, instead of just
having the variable be of type RealInterfaceClass and having to upcast
it to the derived class when I'm using the object.

Thanks
Mustafa
 
J

Jeroen Mostert

MMAS said:
Hey Everyone

I know that I can do something like this in C#
MyClass<WHATEVER>
{
private WHATEVER var_name_of_type_whatever;
public ChangeVar(WHATEVER change_to_value)
{
var_name_of_type_whatever = change_to_value;
}
}

But is there a way to do this?

MyClass<WHATEVER:RealInterfaceClass>
{
private WHATEVER
var_name_of_type_whatever_that_is_forced_to_be_of_basetype_RealInterfaceClass;
public CallMethodThatExistsOnRealInterfaceClass()
{

var_name_of_type_whatever_that_is_forced_to_be_of_basetype_RealInterfaceClass.MethodIKnowExists();
}
}
Yes, it's called constrained genericity. The C# syntax is like this:

class MyClass<T> where T : Type{
...
}

where Type can be either a base class, an interface or another type
parameter. It also supports constraints to indicate that a type must be a
reference (where T : class) or a value type (where T : struct), though these
are less common, and a constraint that a type must have a default
constructor (where T : new()).
 
M

MMAS

Yes, it's called constrained genericity. The C# syntax is like this:

   class MyClass<T> where T : Type{
     ...
   }

where Type can be either a base class, an interface or another type
parameter. It also supports constraints to indicate that a type must be a
reference (where T : class) or a value type (where T : struct), though these
are less common, and a constraint that a type must have a default
constructor (where T : new()).

Great, thanks so much.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top