Question

In C# i would do something like:

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

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

Was it helpful?

Solution

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.

OTHER TIPS

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.

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)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top