views:

213

answers:

3

In C# i would do something like:

mytype val = (mytype)mylistview.SelectedItems(0).Tag;

how can I do the same thing in VB.NET?

+3  A: 

My VB sucks, but I think it would be:

Dim val as MyType = CType(mylistview.SelectedItems(0).Tag, MyType)

or

Dim val as MyType = DirectCast(mylistview.SelectedItems(0).Tag, MyType)

DirectCast doesn't perform any other conversions - including (IIRC) user-specified conversions, whereas CType will perform more conversions than a cast in C# would

In this particular case, I think DirectCast is probably what you're after, as it should be just a reference conversion.

Jon Skeet
+3  A: 

Not sure I'm right not knowing what exactly you're trying to do but general syntax would be:

val = CType(listview.selecteditems(0).tag,mytype)
Justin Wignall
I will, as always, defer to Jon Skeet :)
Justin Wignall
+3  A: 

For the vast majority of cases the CType operator will give the correct behavior here.

Dim val = CType(mylistview.SelectedItems(0).Tag,MyType)

However this is not true in every case. The reason why is that there is no 1-1 mapping between the C# cast operator and an equivalent operator in VB. The C# cast operator supports both CLR and user defined conversion operators.

VB's two main casting operators are DirectCast and CType. DirectCast supports runtime conversions only and will miss user defined ones. CType supports runtime and user defined conversions. But it also supports lexical conversions (such as the string literal "123" to an Integer type). So it will catch everything a C# cast operator does but also include more.

JaredPar