Trouble understanding compiler message on generic where clause

  • Thread starter Thread starter Brad Wood
  • Start date Start date
B

Brad Wood

I have this method declaration:

private SomeType getSomething<T>( T spec ) where T: String, MemoryStream

The compiler error I get is:

'string' is not a valid constraint. A type used as a constraint must be
an interface, a non-sealed class or a type parameter.

I don't understand what is meant by "type parameter" in this context. I
understand a "type parameter" to be my "T" so I don't understand how a
constraint can be the same thing...
 
Hello Brad,

For one, string is sealed so that's why it's not working.

Second, you could do something like this:

public class AClass<T>
{
private void Do<d>(d val) where d : T { }
}
 
Brad Wood said:
I have this method declaration:

private SomeType getSomething<T>( T spec ) where T: String, MemoryStream

The compiler error I get is:

'string' is not a valid constraint. A type used as a constraint must be
an interface, a non-sealed class or a type parameter.

I don't understand what is meant by "type parameter" in this context. I
understand a "type parameter" to be my "T" so I don't understand how a
constraint can be the same thing...

T is the type parameter, and "where T : String, MemoryStream" is the
constraint. However:

1) You can't have a constraint against two classes in the same way as
you can't derive from two classes

2) You can't constrain a type to have a "minimal base type" which is
sealed (like string)
 
Patrik said:
Second, you could do something like this:

public class AClass<T> {
private void Do<d>(d val) where d : T { }
}

Got it; a where constraint can include a reference to a type parameter
other than itself. Thanks.
 
Back
Top