Thursday, January 18, 2007

Automatic Properties Issue On Structs

In general, class objects are allocated on the heap while structs are created on the stack, reference vs. value for short. Their syntax is almost identical, but I found one issue using struct today. Following C# code doesn't compile in Visual Studio 2005:
    struct GeoCode
{
public double Longitude { get; set; }
public double Latitude { get; set; }

public GeoCode(double longitude, double latitude)
{
this.Longitude = longitude;
this.Latitude = latitude;
}
}
The error is:

Backing field for automatically implemented property 'Program.GeoCode.Latitude' must be fully assigned before control is returned to the caller. Consider calling the default constructor from a constructor initializer ...

And:
The 'this' object cannot be used before all of its fields are assigned to ...
It's okay with:
    struct GeoCode
{
public double Longitude;
public double Latitude;

public GeoCode(double longitude, double latitude)
{
this.Longitude = longitude;
this.Latitude = latitude;
}
}
Sounds like the issue of automatic properties on structs in .NET 2.0. To fix it, just follow the error description "Consider calling the default constructor from a constructor..":
    struct GeoCode
{
public double Longitude { get; set; }
public double Latitude { get; set; }

public GeoCode(double longitude, double latitude) : this()
{
this.Longitude = longitude;
this.Latitude = latitude;
}
}