Why am I having to double cast here? - vb.net

I have inheritance structure: Foo implements IGraphNode inherits IGraphItem.
Foo, IGraphItem/IGraphNode, and the implementation for IGraphItem/IGraphNode all reside in separate assemblies. I am using an inversion of control container, so the project I'm working in has a reference to the first two (Foo and IGraphItem/IGraphNode), but not the implementation of IGraphItem/IGraphNode. I also have Option Strict on as it is required for this project (turning if off didn't fix the problem). I'm using .NET 3.5.
I am passing a IGraphItem around and I have code that looks like this:
Public Sub ProcessItem(of IGraphItem)(item As IGraphItem)
If TypeOf item Is Foo Then
Dim f1 = CType(item, Foo) 'Compiler error
Dim f2 = DirectCast(item, Foo) 'Compiler error
'This is what I'm currently having to do. It works.
Dim f = CType(CType(item, IGraphNode), Foo)
'Do stuff
End If
End Sub
Any idea why I'm having to do this? I should add that TryCast works, but since we've just confirmed that item's type is Foo, I don't see why I can't DirectCast it. Shouldn't it just let me and throw an exception if I'm wrong? Is there a better way to accomplish what I'm trying to do?

Your original code compiles without a problem, even when target framework is 3.5.
The problem with your current code is that you've defined a generic method whereas IGraphItem is not the type of your interface but the generic type T which can be any type. But it cannot be another type than T and you're trying to cast it to type Foo.
If you would change your method signature to anything else it would work, for instance:
Public Sub ProcessItem(of IGraphItm)(item As IGraphItem)
I assume that you're somehow "shadowing" the type IGraphItem of your interface with the generic type IGraphItem in this method.
It would also work if you would explicitely tell the compiler that item As IGraphItem actually is a item As YourNamespace.IGraphItem.
I'm sure Jon or Eric could explain it better, but maybe it's helpful anyway ;)

This article might answer your question. If not, well, it's an excellent reading anyway.
http://blogs.msdn.com/b/ericlippert/archive/2009/03/19/representation-and-identity.aspx

Related

What is Office.Tools.Ribbon.RibbonControlImpl?

I am building a small helper to fetch and populate all the controls of a ribbon group inside a collection.
Option Strict On
Imports Microsoft.Office.Tools.Ribbon
Private Function GetChildControls(Group As RibbonGroup) As IEnumerable(Of RibbonControl)
Dim ChildControls As New List(Of RibbonControl)
Dim SubControls As IEnumerable(Of RibbonControl) = Group.Items
ChildControls.AddRange(SubControls)
' ...
' Some recursive call over SubControls to get the children of each child (not relevant here)
' ...
Return ChildControls
End Function
Code breaks at ChildControls.AddRange(SubControls), with the following exception:
System.InvalidCastException: 'Unable to cast object of type Microsoft.Office.Tools.Ribbon.RibbonControl[]' to type Microsoft.Office.Tools.Ribbon.RibbonControlImpl[]'.'
I cannot find any reference at all on RibbonControlImpl. The Microsoft documentation is silent, and - surprisingly - so are Google or StackOverflow.
Changing ChildControls.AddRange(SubControls) into SubControls.ToList.ForEach(Sub(p) ChildControls.Add(p)) does not work either, but a classic For Each does the trick:
For Each MySubControl As RibbonControl In SubControls
ChildControls.Add(MySubControl)
Next
I would like to understand what is happening here? Is Impl a suffix to interface types to signify something? Maybe 'Impl' stands for 'Implementation'? I could not find any information on this either.
Just some thoughts, no idea if I am right; what do you think?
Office.Ribbon.RibbonControl is an interop interface, hence cannot be used as a generic type across assemblies. A guess would be that Microsoft implemented a non-interop RibbonControlImp wrapper to which RibbonControl is implicitly cast every time it is referenced as a generic type.
No idea how this would be achieved, but that would explain why For Each ... Next does not throw the error, whilst relying on generic collections does.

Enforce Type Alias in VB.NET

How might one go about aliasing a type in VB.NET or C# such that when the alias is used as an argument type in a function, accidentally using the not aliased type is an error?
i.e.
Imports AccessSpecifier = System.String
Module Accessors
Delegate Function IoOper(ByRef strm As System.IO.Stream) As Action
Public Function accessMethod(ByRef spec As AccessSpecifier) As IoOper
' implementation
' ...
End Function
End Module
Module Main
Public Sub Main()
Dim spec As AccessSpecifier = New AccessSpecifier(CType("READ_WRITE", Char()))
Dim val = Accessors.accessMethod(spec)
System.Console.WriteLine(val.GetType())
Dim shouldFail = Accessors.accessMethod("FAIL_ME")
System.Console.WriteLine(shouldFail.GetType())
End Sub
End Module
Or perhaps is there a better way to go about this?
Overall, I'm wanting the IDE to force me to know what I'm doing if I'm throwing Ints around to mean Flags, or States and Strings around to mean Names, Propertys and Records.
Help?
I've never liked Type aliasing in .NET. It makes for imprecise code and it is not immediately clear what is happening. As in your example, when an individual went looking for the AccessSpecifier.vb file (or class) they would not find it.
Also, Aliasing only works within YOUR project and only within a single code file. So you would have to define that alias in all the various code files where it was to be used.
A better (as in easier to read, easier to maintain, and more clear of intent) option is to create a class and overload the type conversion operators for automatic conversion to/from String. In this manner you retain your ability to use your new class as if it were a String, but you gain your strict type checking.

GetType not defined?

I'm developing a vb.net program with VS2008. In my case, dt_list is a instance member as List(of Single). When I wrote
dt_list = CType(ser2.Deserialize(r), dt_list.GetType())
VS2008 complains about "Type 'dt_list.GetType()' is not defined.".
Why? Thanks in advance.
The reason this is not allowed is that the exact value of the type for GetType() must be determined at runtime. The second parameter of CType can only be an "expression that is legal within an As clause in a Dim statement, that is, the name of any data type, object, structure, class, or interface", for instance, List(Of String), which can be determined at compile time.
The following is accordingly legal:
dt_list = CType(ser2.Deserialize(r), List(Of Single))
EDIT:
Casting to an arbitrary type, where the type is not known at compile time, is more involved, however. The proposed answer to this question in the MSDN Forums shows one approach. Though it's in C#, I will guess the same approach can be used in VB.NET as well.
What are you trying to achieve by selecting the cast type at runtime?
You may be able to solve your problem with an interface.
Dim dt_list As IList = Ctype(ser2.Deserialize(r), IList)
This gives you access to all of the List members in IList.

Can I include a Generic type parameter in a lamba expression? (VB.NET 2010)

(Not really sure if I phrased the question correctly...)
I want to create a lambda expression that would take an Object, attempt to convert it to a passed-in Type, and print to the console whether it was successful or not.
At a glance, the lambda expression may seem a pretty silly way to accomplish this task, but I'd really like to know what I'm doing wrong, so I can better grow my skill set.
VS gives me a designer error about the second "T" in the expression below, telling me it isn't defined)
This is where I left off:
Sub MyMethod(ByVal param as Object)
Dim quickMethod = Sub (Of T)(o as Object)
Console.WriteLine(TryCast(o, T) IsNot Nothing)
End Sub
quickMethod(Of myClass1)(param)
quickMethod(Of myClass2)(param)
quickMethod(Of myClass3)(param)
quickMethod(Of myClass4)(param)
'further logic below... ;)
End Sub
I can't speak for VB specifically, but I'm not aware of any such concept in .NET delegates in general. While a delegate type can be generic, I don't believe you can leave a particular delegate instance "open" in a type parameter, to be provided by the caller. It's an interesting idea though.
Of course, you could easily write a generic method to do this, and that's probably the right way to go. It's an interesting situation where you could have a single-method interface expressing the desired functionality, but you can't express that as a delegate type. Hmm. Just for the sake of discussion, the interface could be something like this:
interface IConverter
{
bool IsConvertible<T>(object input);
}

How to pass a generic type not having a Interface to a Of T function

I have a following code which works fine
MsgBox(AddSomething(Of String)("Hello", "World"))
Public Function AddSomething(Of T)(ByVal FirstValue As T, ByVal SecondValue As T) As String
Return FirstValue.ToString + SecondValue.ToString
End Function
Now we are redesigning the application to work with parameters of different types which will be provided through XML
<SomeValues>
<Add Param1="Somedata" Param2="SomeData" MyType="String"/>
<Add Param1="Somedata" Param2="SomeData" MyType="MyBusinessObject"/>
</SomeValues>
If I try to provide the following it gives error as Of accepts only type
''''Get DetailsFromXml --- MyType,Param1,Param2
MsgBox(AddSomething(Of Type.GetType(MyType))(Param1,Param2))
How to solve this issue.
Edit
The above example is given to make the question simple. Actual issue is as follows
I am using SCSF of P&P.
Following is per view code which has to be written for each view
Private Sub tsStudentTableMenuClick()
Dim _StudentTableListView As StudentListView
_StudentTableListView = ShowViewInWorkspace(Of StudentListView)("StudentTable List", WorkspaceNames.RightWorkspace)
_StudentTableListView.Show()
End Sub
Now I want to show the views dynamically.
Public Sub ShowModalView(ByVal ViewName As String)
Dim _MasterListView As >>>EmployeeListView<<<<
_MasterListView = ShowViewInWorkspace(Of >>>EmployeeListView<<<)("Employee List", WorkspaceNames.RightWorkspace)
_MasterListView.Show()
End Sub
So the part shown using the arrows above has to be somehow dynamically provided.
The point of generics is to provide extra information at compile-time. You've only got that information at execution-time.
As you're using VB, you may be able to get away with turning Option Strict off to achieve late binding. I don't know whether you can turn it off for just a small piece of code - that would be the ideal, really.
Otherwise, and if you really can't get the information at compile-time, you'll need to call it with reflection - fetch the generic "blueprint" of the method, call MethodInfo.MakeGenericMethod and then invoke it.
I assume that the real method is somewhat more complicated? After all, you can call ToString() on anything...
(It's possible that with .NET 4.0 you'll have more options. You could certainly use dynamic in C# 4.0, and I believe that VB10 will provide the same sort of functionality.)
In .Net generics, you must be able to resolve to a specific type at compile time, so that it can generate appropriate code. Any time you're using reflection, you're resolving the type at run time.
In this case, you're always just calling the .ToString() method. If that's really all your code does, you could just change the parameter type to Object rather than use a generic method. If it's a little more complicated, you could also try requiring your parameters to implement some common interface that you will define.
If all you are doing is ToString, then making the parameters object instead would solve the problem in the simplest way. Otherwise you are going to have to bind the type at run-time, which in C# looks like:
System.Reflection.MethodInfo mi = GetType().GetMethod("AddSomething");
mi = mi.MakeGenericMethod(Type.GetType(MyType));
object result = mi.Invoke(this, new object[] { Param1, Param2 });
Because it involves reflection it won't be fast though... but I assume that's not a problem in this context.