views:

875

answers:

3

Hi,

This is kind of two questions (one more specific than the other).

If I have a method like this:

Public Function Blah(String Foo)
End Function

Can I qualify Foo against another type (for instance can I require that Foo be a String that also implements IInterface?).

I'm imagining something vaguely similar to this:

Public Function Blah(RandomObject Foo Where RandomObject Is IInterface)
End Function

Additionally, is there any way to qualify the Type parameter?

For instance, can I require that the Type I take as a parameter is of a particular class tree?

Public Function Blah(Type t Where Type Of String)
End Function

I should mention that I am using this in the context of a property of an attribute so the class declaration itself cannot be generic (this is purely focused on qualifying a method parameter rather than typing a class and its methods).

A: 

Not sure what you mean by "Foo be a String that also implements IInterface".

string class is sealed, so you can't inherit from it & hence you cant implement an interface on top of it.

I hope I am on the right page.

shahkalpesh
Okay String was a bad example, assume a non-sealed class then.
Graphain
+1  A: 

You can do the first for a generic type, but not for a nongeneric type. Basically a variable (including a parameter) can only have one compile-time type, so you can't say "it has to be a Foo and an IBar - you have to pick one or the other. Generics let you say "it has to be some type T where T derives from Foo and implements IBar" though.

Generics is a huge topic - too big to cover in a Stack Overflow answer - but Microsoft has a good introductory article.

As for your second question - no, you can't do that. The Type value will only be known at execution time, so it has to be an execution time check. You can write that check fairly easily though, with Type.IsAssignableFrom.

Jon Skeet
Thanks - I thought I understood generics well enough but I couldn't seem to get the VB.NET syntax right for qualifying a method unless I qualified the class too. As for the Type check, I guess this is one thing compilers could work on but you're right I didn't consider dynamic typing.
Graphain
+2  A: 

This looks like a case for generics to me. Your method signature would be something like this in VB.NET:

Public Function Blah(Of T As {IImplementedByT})(Foo As T)

This specifies that Foo can be of any type T as long as T implements IImplementedByT. Note that this method can be generic without the containing class needing to be generic. If you want T to be a class derived from RandomClass that also implements this interface, you can specify both constraints:

Public Function Blah(Of T As {RandomClass, IImplementedByT})(Foo As T)
David M
Thanks - this was interesting and useful but I found out what I wanted to do was something else. I was trying to apply this to properties but you can't have type parameters on a set clause.
Graphain