Remember variant ?

Posted Thu, Jul 28 2011 14:40 by bill

Cory is continuing his posts about VB10 differences from VB6. His latest posts is on variants.

Variants were/are basically a structure that contains a variant type enumeration and either the variable’s data value or a pointer to the variable data. In pseudo code it basically looks like:

Structure Variant
    Public VT as VariantType
    Public Value As Object
End Structure

The Value field would hold the actual data in the case of simple value types, or a  pointer to the object such as in the case of arrays. In the .NET world there are actually variant structures but not as part of the .Net framework: you can find one for example in the Microsoft.VisualStudio.Package namespace.

The reason you won’t find it in the framework is because the variant structure is not only limited but also superfluous in .NET due to the type system. Take for example the case of a value as a Double versus an Integer. In VB6 you would use Variant to allow you to pass both values to a method. The Value field would hold the actual data so it was important that the VT field told you the value type. The problem with this approach is the VT field is an enumeration, so doesn’t allow for custom value types to have their actual type discoverable: try passing a UDT into a variant and then determining which type of UDT is is in VB6 to see what I mean Winking smile

In .NET the object based type system means you can always determine the type of a variable. So the “everything stems from Object” approach in .NET is definitely more versatile.

There was however one thing missing: yep, IsMissing was missing. Variants allow optional parameters to indicate if a value was missing. The first release of .Net didn’t have anything in place to indicate if an optional parameter was missing. It wasn’t until nullable types were added that you could do the equivalent of IsMissing by testing for Is Nothing. The Is Nothing approach is more holistic and uniform (as opposed to IsEmpty versus IsMissing et al) and works across the board for nullable types and As Object variables and parameters.

So, in summary, there was initially some gains and some losses with the move from Variant to an Object based system, but as the .NET framework and language implementations have matured, the Object based system (.NET) offers far more functionality and flexibility.

Oh, as you can probably see, the above explanation/description actually touches on a number of items in the list Cory referred to: in particular but not limited to items 11 and 27. I think it is always important to come up for air and see the big picture: the forest from the trees. The overall benefits of moving to Object based in .NET extend far beyond these one or two items.

Filed under: , , , , ,