Sunday, November 2, 2008

Structure Usage Guidelines

It is recommended that you use a structure for types that meet any of the following criteria:
1. Act like primitive types.
2. Have an instance size under 16 bytes.
3. Are immutable.
4. Value semantics are desirable.
The following example shows a correctly defined structure.
Visual Basic
Public Structure Int32
Implements IFormattable
Implements IComparable
Public Const MinValue As Integer = -2147483648
Public Const MaxValue As Integer = 2147483647
Private intValue As Integer
Overloads Public Shared Function ToString(i As Integer) As String
' Insert code here.
End Function
Overloads Public Function ToString(ByVal format As String, _
ByVal formatProvider As IFormatProvider) _
As String Implements
IFormattable.ToString
' Insert code here.
End Function
Overloads Public Overrides Function ToString() As String
' Insert code here.
End Function
Public Shared Function Parse(s As String) As Integer
' Insert code here.
Return 0
End Function
Public Overrides Function GetHashCode() As Integer
' Insert code here.
Return 0
End Function
Public Overrides Overloads Function Equals(obj As Object) _
As Boolean
' Insert code here.
Return False
End Function
Public Function CompareTo(obj As Object) As Integer _
Implements IComparable.CompareTo
' Insert code here.
Return 0
End Function
End Structure
C#
public struct Int32: IComparable, IFormattable
{
public const int MinValue = -2147483648;
public const int MaxValue = 2147483647;
public static string ToString(int i)
{
// Insert code here.
}
public string ToString(string format,
IFormatProvider formatProvider)
{
// Insert code here.
}
public override string ToString()
{
// Insert code here.
}
public static int Parse(string s)
{
// Insert code here.
return 0;
}
public override int GetHashCode()
{
// Insert code here.
return 0;
}
public override bool Equals(object obj)
{
// Insert code here.
return false;
}
public int CompareTo(object obj)
{
// Insert code here.
return 0;
}
}
When using a structure, do not provide a default constructor. The runtime will insert a constructor that initializes all the values to a zero state. This allows arrays of structures to be created more efficiently. You should also allow a state where all instance data is set to zero, false, or null (as appropriate) to be valid without running the constructor

No comments: