There are few idioms and constructs that Visual Basic .NET cannot touch. Although not especially good at pointers and addresses, VB .NET and C# enable a developer to emulate, contrive, or precisely reproduce almost everything else that even the most complex languages, such as C++, offer.
One such construct is the union. A union is like a structure, but it permits all its fields to share the same starting address. Consider a union with character and integer fields. The union structure would be 32 bits; that is, the union would be the size of the largest element. Assign a value to the char (say, 65) and the union would assign the integer the same value. When accessed through the integer field, it would return the value 65. When accessed through the character field, it would return the value A. Change one field and the other changes as well. Peter Norton did some famous work with unions that resulted in the now ubiquitous undelete application.
Although the most common reason to use a union probably is to map more than one field to the same memory address, you are not limited only to this use. This article demonstrates how to implement the union construct in VB .NET. You'll know when you need it.
The union construct commonly is used to map more than one cardinal field to the same address. After all, cardinal fields (or numbers) overlap nicely. However, the most common application in .NET likely will be for interop—that is, using code that was written in something other than .NET. Whenever you use interop code, you use the System.Runtime.InteropServices namespace. It contains a lot of interesting code, including the Marshal class. For the example in this article, you add an Imports statement, but you should explore this namespace further on your own.
- Add the Imports System.Runtime.InteropServices statement.
- Define a structure (Union, in this example).
- Apply the StructLayoutAttribute with LayoutKind.Explicit to the structure.
- Add two fields to the structure: an integer and a character.
- Apply the FieldOffsetAttribute to each of the fields, initializing the attribute with 0.
You are not limited to using integers and characters. You can use other types too, but you cannot mix reference types such as Object and String with value types like integer and char.
- Auto means that the layout is automatic and the type cannot be exported outside of managed code.
- Explicit means that you will define the layout of fields explicitly using the FieldOffsetAttribute. Explicit layout is used to position fields precisely, mapping managed types to unmanaged types.
- Sequential is used to lay out members in order of appearance. Sequentially laid out fields do not have to be contiguous.
Union for VB .NET Programmers
VB .NET supports manufacturing even the advanced union idiom, which you previously found in languages like C and C++. Unions permit VB .NET programmers to overlap fields, which is useful when calling unmanaged code that returns a union.