Tuesday, November 19, 2013

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

Working with structs in C# gives you a lot of flexibility on the way you design your applications, but since they are not reference types, they have some special features that we need to take in count.
Recently I was working on a web application and I created a struct to hold a pair of values that is being used very frequently. It is something like this

public struct StringTuple{
    public string Value1 {get; set;}
    public string Value2 {get; set;}
}
After some code changes, I decided that it would be a good option to have a constructor to pass the struct values
public struct StringTuple
{
 public StringTuple(string value1, string value2)
 {
  Value1 = value1;
  Value2 = value2;
 }
 public string Value1 { get; set; }
 public string Value2 { get; set; }
}
but the compiler started complaining, giving me the following error
Backing field for automatically implemented property Value1 must be fully assigned before control is returned to the caller
It was the first time that I had seen that error, so after some time of think and research I remembered one of the basic principles of working with structs: members are initialized when the default constructor is called. That is why creating a new constructor was creating a problem, since we were overloading the constructor call and skipping that member initialization

The solution

Since the problem is that we're not calling the default constructor, the solution is obviously call it, so we just need to add that call to the constructor that we just introduced.
public struct StringTuple
{
 public StringTuple(string value1, string value2):this()
 {
  Value1 = value1;
  Value2 = value2;
 }
 public string Value1 { get; set; }
 public string Value2 { get; set; }
}
By that, the error message is gone and we can continue happily working with structs

Unknown

Software developer with main experience in Microsoft Technologies but who also enjoys working with other languages. More about me

0 comentarios:

Post a Comment

 

Copyright @ 2013 A learning journey.