A number of recent customer comments have made it clear that some confusion surrounds the use of constructors with value types. Most common are the complaints that we've failed to document a constructor for a particular value type. In one case, though, a customer asked that we remove the documentation on constructors for value types, since he or she was certain that they are not supported by the .NET Framework. Just as you can define parameterized constructors for reference types, you can define parameterized constructors for value types. For example, the following code defines a VehicleInfo structure that has two parameters: the number of wheels on a vehicle, and its number of doors. [Visual Basic]Public Structure VehicleInfo
Private nWheels As Integer
Private nDoors As Integer Public Sub New(ByVal wheels As Integer, ByVal doors As Integer)
nWheels = wheels
nDoors = doors
End Sub Public ReadOnly Property NumberOfWheels() As Integer
Get
Return nWheels
End Get
End Property Public ReadOnly Property Doors() As Integer
Get
Return nDoors
End Get
End Property
End Structure [C#]using System;
public struct VehicleInfo
{
private int nWheels;
private int nDoors; public VehicleInfo(int wheels, int doors)
{
nWheels = wheels;
nDoors = doors;
} public int NumberOfWheels
{
get { return nWheels; }
} public int Doors
{
get { return nDoors; }
}
}The example compiles normally, and when we use IL DASM to examine our type, we can see that it includes the parameterized constructor.Read more: BCL Team Blog
Private nWheels As Integer
Private nDoors As Integer Public Sub New(ByVal wheels As Integer, ByVal doors As Integer)
nWheels = wheels
nDoors = doors
End Sub Public ReadOnly Property NumberOfWheels() As Integer
Get
Return nWheels
End Get
End Property Public ReadOnly Property Doors() As Integer
Get
Return nDoors
End Get
End Property
End Structure [C#]using System;
public struct VehicleInfo
{
private int nWheels;
private int nDoors; public VehicleInfo(int wheels, int doors)
{
nWheels = wheels;
nDoors = doors;
} public int NumberOfWheels
{
get { return nWheels; }
} public int Doors
{
get { return nDoors; }
}
}The example compiles normally, and when we use IL DASM to examine our type, we can see that it includes the parameterized constructor.Read more: BCL Team Blog
0 comments:
Post a Comment