Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automatically implemented property in struct can not be assigned

Tags:

I have a next code:

struct T  {     public T(int u)      {          this.U = 10; //Errors are here     }      public int U { get; private set;  } } 

C# compiler give me a pair of errors in stated line: 1) Backing field for automatically implemented property 'TestConsoleApp.Program.T.U' must be fully assigned before control is returned to the caller. Consider calling the default constructor from a constructor initializer. 2) The 'this' object cannot be used before all of its fields are assigned to

What I do wrong? Help me understand.

like image 668
Vasya Avatar asked Oct 06 '11 06:10

Vasya


People also ask

How do you auto implement property?

Auto-implemented properties declare a private instance backing field, and interfaces may not declare instance fields. Declaring a property in an interface without defining a body declares a property with accessors that must be implemented by each type that implements that interface.

What is an automatic property and how is it useful?

What is automatic property? Automatic property in C# is a property that has backing field generated by compiler. It saves developers from writing primitive getters and setters that just return value of backing field or assign to it.

What is backing field in C#?

A private field that stores the data exposed by a public property is called a backing store or backing field. Fields typically store the data that must be accessible to more than one type method and must be stored for longer than the lifetime of any single method.

What is property C#?

A property is a member that provides a flexible mechanism to read, write, or compute the value of a private field. Properties can be used as if they're public data members, but they're special methods called accessors.


1 Answers

From the C# Specification:

10.7.3 Automatically implemented properties

When a property is specified as an automatically implemented property, a hidden backing field is automatically available for the property, and the accessors are implemented to read from and write to that backing field.

[Deleted]

Because the backing field is inaccessible, it can be read and written only through the property accessors, even within the containing type.

[Deleted]

This restriction also means that definite assignment of struct types with auto-implemented properties can only be achieved using the standard constructor of the struct, since assigning to the property itself requires the struct to be definitely assigned. This means that user-defined constructors must call the default constructor.

So you need this:

struct T  {     public T(int u)         : this()     {          this.U = u;     }      public int U { get; private set; } } 
like image 59
Enigmativity Avatar answered Oct 01 '22 13:10

Enigmativity