Introduction
Working with struct
s 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 into account.
Recently, I was working on a web application and I created a struct
to hold a pair of values that are 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 thinking and research, I remembered one of the basic principles of working with struct
s: 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 struct
s.
CodeProject