Tuesday 22 April 2008

Automatic Properties and Structs

I was merrily creating my first struct since the advent of automatic properties and figured it would be nice and easy, so continued and created the following:

public struct UserNamePasswordPair
{
public string UserName { get; set; }
public string Password { get; set; }

public UserNamePasswordPair(string userName, string password)
{
UserName = userName;
Password = password;
}
}



To my disappointment I got a compiler error:



"The 'this' object cannot be used before all of its fields are assigned to"



This was very disappointing and I thought surely Microsoft wouldn't have forgotten to allow automatic properties on structs and it turns out they haven't, looking further down the error list I see a useful message:



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



Ah ha, fair enough, so I simply added the call to the default constructor and bobs you uncle it compiled, yeh!



public struct UserNamePasswordPair
{
public string UserName { get; set; }
public string Password { get; set; }

public UserNamePasswordPair(string userName, string password)
: this()
{
UserName = userName;
Password = password;
}
}

3 comments:

Anonymous said...

The two blocks of example code are the wrong way round.

Richard Allen said...

Thanks for pointing that out, I have amended the code blocks.

Anonymous said...

Great solution..
Thank you!