Mark Leavesley
Mark Leavesley

Reputation: 61

How can I do C style casting in VB.NET?

I have a object type variable (control .Tag) that I need to cast to a structured type, and change a member in. This is a contrived but representative example:

Public Structure struct_COLOURS
  Dim ILikeRed as boolean
  Dim ILikeGreen as boolean
End Structure

Dim AnObject as Object = (some source that is struct_COLOURS)

DirectCast(AnObject, struct_COLOURS).ILikeRed = True ' This is not valid syntax?!

I don't remember my C syntax very well, but it would be something like this:

(struct_COLOURS*)AnObject->ILikeRed = true;

The point is I can cast an object to something and set members in the resulting cast. It seems as though DirectCast is actually a function and is not casting in the way I would interpret it.

Oddly, if you only want to retrieve a member value, you can use DirectCast:

dim YummyRed AS Boolean = DirectCast(AnObject, struct_COLOURS).ILikeRed

is just fine!

If I cannot cast the way I want, and I cannot change the use of the Tag property (so please don't suggest, it's not an option) to store these structures, what is the fastest way to set members?

Upvotes: 3

Views: 247

Answers (2)

Marko
Marko

Reputation: 10992

That's how you should cast - with CType:

Dim myColor As Object = Nothing
        Dim color As Color = CType(myColor, Color)
        color.Name = "red"

Why a struct and not a class?

Upvotes: -2

Konrad Rudolph
Konrad Rudolph

Reputation: 545588

It seems as though DirectCast is actually a function and is not casting in the way I would interpret it.

No, that’s wrong: DirectCast isn’t a method, it’s a real language construct, like a cast in C.

However, if you store a structure (= value type) in an object, it gets boxed and, by consequence, copied. This is causing the problem here: you’re attempting to modify a copy, not the original, boxed object.

So in order to change a member of a boxed value type object, you need to copy the object, change its value, and copy it back:

Dim tmp = DirectCast(AnObject, struct_COLOURS)
tmp.ILikeRed = True
AnObject = tmp

Incidentally, the same is true in C#, despite the superficial similarity to the C cast syntax.

Upvotes: 7

Related Questions