Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#

Backing Field for Automatically Implemented Property [Field] must be Fully Assigned Before Control is Returned to the Caller

4.50/5 (3 votes)
20 Nov 2013CPOL1 min read 17.2K  
Backing Field for Automatically Implemented Property [Field] must be fully assigned before Control is returned to the caller

Introduction

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 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:

C#
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:

C#
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 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.

C#
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.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)