Can I qualify a parameter type in VB.NET?

These are two questions (one specific than the other).

If I have a method like this:

Public Function Blah(String Foo) End Function 

Is it possible to qualify Foo against another type (for example, I can require Foo to be a String that also implements IInterface?).

I imagine something like this:

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

Also, is there a way to qualify the Type parameter?

For example, can I require Type to accept a specific class tree as a parameter?

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

I should mention that I use this in the context of an attribute property, so the class declaration itself cannot be general (this is purely focused on selecting a method parameter, and not on entering the class and its methods).

+4
source share
3 answers

This is similar to the case for generics. Your method signature will be like this in VB.NET:

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

This indicates that Foo can be of any type T, if T implements IImplementedByT. Note that this method can be generic without a class that must be generic. If you want T to be a class derived from RandomClass that also implements this interface, you can specify both restrictions:

 Public Function Blah(Of T As {RandomClass, IImplementedByT})(Foo As T) 
+3
source

You can do the first for the generic type, but not for the inappropriate type. Basically, a variable (including a parameter) can have only one type of compilation time, so you cannot say "it must be Foo and IBar - you need to choose one or the other. Say," it must be some type T , where T comes from Foo and implements IBar . "

Generics is a huge topic, too big to cover in response to a stack overflow, but Microsoft has a good introductory article .

As for the second question - no, you cannot do this. The Type value will only be known at runtime, so it should be a check of the runtime. You can write this check quite easily, but Type.IsAssignableFrom .

+1
source

Not sure what you mean by "Foo be String, which also implements IInterface."

The string class is sealed, so you cannot inherit it, and therefore, you cannot implement an interface on top of it.

Hope I'm on the right page.

0
source

All Articles