Can I qualify the type of a parameter in VB.NET? - vb.net

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

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)

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.

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.

Related

How to extend derived classes by defining class(es) that exposes the instance as a property

I have a class that I would like to extend by defining a new class that contains the first class as a public property, as well as additional added properties. However, the class that I'm extending has multiple derived types, which should be treated the same in the extension class.
Below is an example of what I am trying to do:
Public Class ClassA
End Class
Public Class ClassB
Inherits ClassA
End Class
Public Class ClassC
Inherits ClassA
End Class
Public Class BaseExtended
Public Property Foo As ClassA
Public Property ExtendedMetaData1 As Double
Public Property ExtendedMetaData12 As Integer
End Class
Public Class DerivedExtendedB
Inherits BaseExtended
Public Property Foo As ClassB
End Class
Public Class DerivedExtendedC
Inherits BaseExtended
Public Property Foo As ClassC
End Class
The code that uses an instance of any of the 'extended' classes would then need use that instance appropriately depending on it's type. There would be many cases where the property 'Foo' needs to be accessed and modified outside of the class that it belongs to.
If I were to implement something like what I have shown above, that would require that I first cast it to the required type before accessing or modifying it. Ideally I would like to do that inside the 'DerivedExtended' class; The alternative, I think, would be to duplicate code to cast that property would [hundreds of times] in the client code.
Private Sub ClientUsesObject(bar As BaseExtended)
' Perform a task that is agnostic Foo type
' Would not require that Foo be cast to any specific type
If bar.GetType() Is GetType(DerivedExtendedB) Then
Dim barCast As DerivedExtendedB = DirectCast(bar, DerivedExtendedB)
' Perform task that requires Foo to be of type ClassB
ElseIf bar.GetType() Is GetType(DerivedExtendedC) Then
Dim barCast As DerivedExtendedC = DirectCast(bar, DerivedExtendedC)
' Perform task that requires Foo to be of type ClassC
End If
End Sub
What I'm looking for is advice outlining or describing a design pattern that can handle this situation. I've searched for quite a while, and have not been able to find any examples that solve this problem.
I realize that this may be somewhat of an "XY" problem. I'm working with existing code that simply assumes all instances are of the same derived type (when in fact some instances are of the other derived type). As such, the existing code does not work. To me what I've tried to outline above seems like the most straightforward path, but I'm open to alternative if this is just the wrong approach.
This pattern of type covariance in derived classes is the canonical reason for what is called in C++ the "Curiously Recurring Template Pattern" and has been called in .NET the "Curiously Recurring Generic Pattern." I believe it's also sometimes referred to as "F-Bounded Polymorphism" (not a computer scientist, so I might have the reference wrong).
You can write a base class like this:
Public Class Base(Of TDerived As Base)
Public Overridable Property foo As TDerived
End Class
And then use it like this:
Public Class MyDerived
Inherits Base(Of MyDerived)
End Class
Then, the derived class has a property foo whose type is MyDerived. No casting required by clients.
However, this has some limitations. It works best when you don't need to switch back and forth between derived and base. There is no one Base, so you can't declare instances of it. If you want to be able to declare something as Base, then you end up needing to fall back on a non-generic base class. This will still work well for certain usage patterns where you don't need to convert from base to derived, but otherwise you run right back into the casting problems you are trying to avoid.
Eric Lippert has written a bit about this pattern. He's always interesting to read, so I'd recommend looking up his commentary.
Another alternative to consider, if the generic approach doesn't work for you, is code generation. You can use T4 templates to process a compact description of what your code should be, and generate the code files from them. A long list of casts is less tedious if you only write the machinery to generate it, you don't write them all out explicitly.

Why can't I cast a generic parameter with type constraint to the constrained type?

I am getting used to using interfaces, generics and develping them using inheritance in a real envrionment whilst trying use and implement this into a new architecture for one of our upcoming projects and I have a question regarding generics which I am confused about.
This is more of a educational question for myself because I can't understand why .NET doesn't allow this.
If I have a generic class which is (Of T As IA, T2 As A) then I have the following interfaces and class which implements the base interface
Public Interface IA
Property A As String
End Interface
Public Interface IB
inherits IA
Property B As String
End Interface
Public Class GenericClass(Of T As IA, T2 As A)
'Should be list of IA?
Public list As New List(Of T)
Public Sub Add()
End Sub
End Class
Because I have made T as IA why in the add method is Dim foo4 As T = New A() not legal when
Dim foo1 As IA = New A()
Dim foo2 As T
Dim foo3 = Activator.CreateInstance(Of T2)()
Dim x As IA = foo2
Dim y As IA = foo3
list.Add(x)
list.Add(y)
All of the above is? This is becoming a learning curve for me with generics etc. but I am just very confused with why I logically can't do this?
EDIT: Sorry forgot Class A and error message please see below
Public Class A
Implements IA
Public Property A As String Implements IA.A
End Class
EDIT 2: Error was typed incorrectly
"Value of type class a cannnot be converted to T"
It's not exactly clear what you're trying to do, but one problem I notice is that you seem to be assuming that a List<TypeThatImplementsIA> is somehow interchangeable with a List<IA>. That is not the case. Imagine that A were a class of flying birds, and IA were implemented by creatures that can fly, and someone created a GenericClass<Airplane, BlueJay). Even though Airplane and BlueJay are both things that can fly, one would not be able to add a BlueJay to a List<Airplane>. The one common situation in the Framework where one can use a GenericType<DerivedType> as a GenericType<BaseType> is with IEnumerable<T>. The reason for that is that one can't store T's into an IEnumerable<T>--one can only read them out. If one is expecting an IEnumerable<Animal> and one is given an IEnumerable<MaineCoonCat>, then every time one expects to read an Animal, one will read an instance of MainCoonCat, which inherits from Animal and may thus substitute for it. This feature of IEnumerable<T> is called covariance.
There's a limitation to such behavior, though, which stems from the fact that there is a difference between using an interface as a type of storage location (variable, parameter, etc.), versus using it as a constraint. For every non-nullable value type, there are actually two related types within the Runtime. One of them is a real value type, which has no concept of inheritance (but can implement interfaces). The other is a heap-object type which derives from ValueType (which in turn derives from Object). Most .net languages will implicitly convert the former type to the latter, and allow code to explicitly convert the latter to the former. Interface-type storage locations can only hold references to heap objects. This is significant because it means that while a struct which implements an interface is convertible to that interface type, that doesn't mean instance of the struct is an instance of that interface type. Covariance works on the premise that every object returned by e.g. an IEnumerable<DerivedType> may be used directly as an instance of BaseType without conversion. Such direct substitutability works with inherited class types, and with interfaces that are implemented by class types. It does not work with interfaces implemented by struct types, or with generics that do not have a class constraint. Adding a class constraint to a generic class type parameter will allow that type parameter to participate in covariance, but may preclude the use of structs as the generic type parameter. Note that unless one has particular reason to expect that an interface will be implemented by structures (as is the case with e.g. IComparable<T>, in many cases it's unlikely that an interface would be implemented by a structure and thus a classconstraint would be harmless).
That's because T is not the interface IA itself. It is one implementation of it.
Suppose that you have another class that implements IA:
Public Class B
Implements IA
Public Property B_A As String Implements IA.A
Public Property OtherProperty as Object
End Class
Then you create a new instance of Generic Class like this:
Dim genericObject as new GenericClass(Of B, A)
So in this case, T now is B, and A cannot be casted to B.
In this case instead, replacing the part of your doubt, a code that would make sense for me:
Dim foo4 As IA = New T()
EDIT due to comment
To be able to instantiate T, it is necessary to declare the New constraint in the type definition. So the generic class declaration would be:
Public Class GenericClass(Of T As {New, IA}, T2 As A)

VB.NET - I'm Refactoring and Could Use Some Help

I'm working with vb.net, wcf, wpf and I'm refactoring working code with the hope of being able to reduce some amount of redundancy. I have a bunch of methods that get called in several places throughout the code that only have a slight variation from each other and I would like to replace them with a single method instead.
Specifically, each of the redundant methods process an 1-d array that contain different objects I have created. There are several of these different object types each with different signatures but they have all have a "name" and "Id" property. (Also these objects don't have a shared base class but I could add that if needed.) Each of the redundant methods deal with a different one of the object types.
To refactor the code I would like to pass any of the different object arrays to a single new method that could access the "name" and "id" properties. I'm trying to write this new method in a fashion that wouldn't require me to update it if I created more objects down the road.
I've done some reading on Delegates and Generic Classes but I can't really figure out how this fits in. It would almost be as if I wanted to create a generic class that could handle each of my object types but then somehow also access the "name" and "id" propeties of the different object types.
Any help you can provide would be appretiated. Also, please keep in mind this project is written in VB.net.
Thanks
Mike
It sounds like having your object implement a common interface or have a shared base class would be best. Interfaces give you the most flexibility down the road if you ever need to pass a class to this method that must derive from some other class that does not implement the interface. However, a base class that implements the interface may also be useful just to reduce the duplicate declarations of these properties.
Public Interface IThingThatHasNameAndId 'good name not included
ReadOnly Property Name As String
ReadOnly Property Id As Integer
End Interface
Once you have the interface, you can then pass arrays of types implementing the interface as IEnumerable(Of IThingThatHasNameAndId) or make a generic method taking T() and constrain T to the interface.
Make a base class with the Name and ID properties, then you can make a method that takes in any class that derrives from that class.
Public Function TestFunction(Of t As YourBaseClass)(Byval obj As t) As Boolean
If obj.Name = "Some Name" AndAlso obj.ID = 1 Then
Return True
Else
Return False
End If
End Function

More specific Type from base shared constructor

How do I get using reflection the most generic type from a shared constructor in the base class :
Public Class Foo()
Shared Sub New()
'Here we have code to get the type!
MethodBase.GetCurrentMethod().DeclaringType
End
End Class
Public Class Bar()
Inherits Foo
End Class
I expect the result to be Bar type and not the Foo. Is it possible?
First, it seems you want to find the most derived type (or the most specific type), not the most generic type -- which would mean rather the opposite (either, that generics are involved, or that the most general type is being sought).
While it may be possible to do this using reflection, your need for it might indicate that you have your class design wrong, or less than optimal.
First, constructors aren't virtual methods, so inside a constructor (IIRC), the Me object reference is of the type that contains this constructor.
What you could do is reflect over all of an assembly's types and find all those that are derived from Foo. You would then have to build a inheritance graph of these types and assign a number to each saying how far it is derived from Foo (number of inheritance levels). You could then check the Me object reference against all of the types you've identified (see if Me can be cast to each of them), and from that subset, choose the one type with the largest number of inheritance levels.
I hope that from this, you'll see that it's probably not worth the effort. It would be more interesting, and probably more helpful, to re-think why you need to do this, and if possible, find a way to avoid it.

MyClass in VB.Net

What is a realistic use for VB.Net's MyClass keyword?
I understand the technical usage of MyClass; I don't understand the practical usage of it in the real world.
Using MyClass only makes sense if you have any virtual (overridable) members. But it also means that you want to ignore the overridden implementations in sub classes. It appears to be self-contradicting.
I can think of some contrived examples, but they are simply bad design rather than practical usage.
MyClass, from a compiler's perspective, is a way to omit a callvirt instruction in favor of a call instruction. Essentially when you call a method with the virtual semantics (callvirt), you're indicating that you want to use the most derived variation. In cases where you wish to omit the derived variations you utilize MyClass (call). While you've stated you understand the basic concept, I figured it might help to describe it from a functional viewpoint, rather than an implicit understanding. It's functionally identical to MyBase with the caveat of scope being base type with MyBase, instead of the active type with MyClass.
Overriding virtual call semantics, at the current point in the hierarchy, is typically a bad design choice, the only times it is valid is when you must rely on a specific piece of functionality within your object's hierarchy, and can't rely on the inheritor to call your variation through a base invocation in their implementation. It could also rely on you as a designer deciding that it's the only alternative since you overrode the functionality further in the object hierarchy and you must ensure that in this corner case that this specific method, at the current level of the inheritance tree, must be called.
It's all about design, understanding the overall design and corner cases. There's likely a reason C♯ doesn't include such functionality since on those corner cases you could separate the method into a private variation the current level in the hierarchy invokes, and just refer to that private implementation when necessary. It's my personal view that utilizing the segmentation approach is the ideal means to an end since it's explicit about your design choice, and is easier to follow (and it's also the only valid means in languages without a functional equivalent to MyClass.)
Polymorphism
I'm sorry I don't have a clear code example here but you can follow the link below for that and I hate to copy the MSDN Library description but it's so good that it's really hard to rewrite it any clearer.
"MyClass provides a way to refer to the current class instance members without them being replaced by any derived class overrides. The MyClass keyword behaves like an object variable referring to the current instance of a class as originally implemented."
Also note that you can't use MyClass in a shared method.
A good example of implementing Polymorphism via MyClass is at http://www.devarticles.com/c/a/VB.Net/Implementing-Polymorphism-in-VB.Net/
I guess the only case I could see a use for it, would be if you want the base condition, and an inherited condition at the same time? I.E. where you want to be able to inherit a member, but you want the ability to access a value for that member that hasn't been changed by inheritance?
You need it if you want to call a chained constructor.
Public Sub New(ByVal accountKey As Integer)
MyClass.New(accountKey, Nothing)
End Sub
Public Sub New(ByVal accountKey As Integer, ByVal accountName As String)
MyClass.New(accountKey, accountName, Nothing)
End Sub
Public Sub New(ByVal accountKey As Integer, ByVal accountName As String, ByVal accountNumber As String)
m_AccountKey = accountKey
m_AccountName = accountName
m_AccountNumber = accountNumber
End Sub