What's wrong with defining this type of Struct

I defined my structure as follows:

struct Test
{
    private string assayName;
    public string AssayName { get; set; }

    private string oldUnitName;
    public string OldUnitName { get; set; }

    private string newUnitName;
    public string NewUnitName { get; set; }

    public Test(string name, string oldValue, string newValue)
    {
        assayName = name;
        oldUnitName = oldValue;
        newUnitName = newValue;
    }

}

but this gives me the following error:

"Error 13 The backup field for the automatically implemented property 'EnterResults.frmApplication.Test.NewUnitName' must be fully assigned before control returns to the caller. Consider calling the default constructor from the constructor initializer."

+5
source share
5 answers

Well, there are two problems:

1. Using automatic properties, but then also providing fields, there is no wiring between them.

2. , , . . , :

struct Test
{
    public Test(string name, string oldValue, string newValue)
        : this()
    {
        AssayName = name;
        OldUnitName = oldValue;
        NewUnitName = newValue;
    }

    public string AssayName { get; private set; }
    public string OldUnitValue { get; private set; }
    public string NewUnitValue { get; private set; }
}
+6

. :

struct Test 
{ 
    public string AssayName { get; set; } 
    public string OldUnitName { get; set; } 
    public string NewUnitName { get; set; } 

    public Test(string name, string oldValue, string newValue) : this()
    { 
        AssayName = name; 
        OldUnitName = oldValue; 
        NewUnitName = newValue; 
    } 
} 

, . , , , :)

", " - . , , . .

+6

private assayName, oldUnitName newUnitName. :

public Test(string name, string oldValue, string newValue)
{
    AssayName = name;
    OldUnitName = oldValue;
    NewUnitName = newValue;
}
+3

You try to create an automatically implemented property , but you define "fallback fields" (which are not explicitly used), and then you assign values ​​to those supporting fields in your constructor and leave your properties completely untouched.

+2
source

You can also call the default constructor:

public Test(string name, string oldValue, string newValue) : this() 
{
   assayName = name;
   oldUnitName = oldValue;
   newUnitName = newValue;
}

Look here

+2
source

All Articles