Tuesday, February 10, 2009

Structs and Anonymous backing fields

I got this error today

Backing field for automatically implemented property must be fully assigned before control is returned to the caller.

I found a strange thing out today in connection with Structs and anonymous fields. I wanted something simple like

public struct Person
{
public String FirstName { get; set; }
public String LastName { get; set; }
public Int16 Age { get; set; }

public Person(String firstName, String lastName, Int16 age)
{
FirstName = firstName;
LastName = lastName;
Age = age;
}
}


well that won’t compile as you will need to initialise all of the fields, so you have to do this – notice the call to the default constructor.



public struct Person
{
public String FirstName { get; set; }
public String LastName { get; set; }
public Int16 Age { get; set; }

public Person(String firstName, String lastName, Int16 age): this()
{
FirstName = firstName;
LastName = lastName;
Age = age;
}
}

Maybe the compiler should not allow anonymous fields in structs?

No comments: