Trouble understanding compiler message on generic where clause

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...
 
?

=?iso-8859-1?Q?Patrik=20L=f6wendahl=20[C#=20MVP]?=

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 { }
}
 
J

Jon Skeet [C# MVP]

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)
 
B

Brad Wood

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.
 

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