简体   繁体   中英

Strange behavior of Struct in C#

I have a structure as below. I have few problems

Problem1:

struct MyStruct 
{
    public MyStruct(int a)
    {
        this.a = a;
        this.b = 10;
    }
    public int a;
    public int b;
}

When I remove this.b from MyStruct constuctor it will give me an error "Field must be fully assigned before control is returned to the caller". but in case of class it doesn't occur

Problem2:

struct MyStruct 
{
    //public MyStruct(int a)
    //{
    //      this.a = a;
    //      this.b = 10;
    //}
    //int asd;
    //public int MyProperty { get; set; }
    public void getImplemen()
    {
        Console.WriteLine("azsdfa");
    }
    public int a;
    public int b;
}

static void Main(string[] args)
{
    MyStruct myStruct ;
    myStruct.a = 15;//when I comment this it will give an error
    myStruct.b = 15; //when I comment this it will give an error
    myStruct.getImplemen();
}

When I change MyStruct myStruct to MyStruct myStruct = new MyStruct (); it works fine.

why so?

That's just how it goes.

Default constructor initializes every field to a default value, while a constructor with parameters forces you to initialize every field in the struct.

What if you have a default constructor AND one with parameters, you ask? Well, I don't remember. Easy enough to check on your own.

It does not allocate memory for fields:

MyStruct myStruct;

Allocates memory and initialize fields in constructor:

MyStruct myStruct = new MyStruct();

If you does not allocate memory for a variable then you can not assign a value to the fields. Сonstructor allocate memory and initializes fields (you need initialize fields in constructor before control is returned to the caller).

you should refer to https://msdn.microsoft.com/en-us/library/aa288471(v=vs.71).aspx

you need to create the instance of your struct before using it.

The difference is that structs are value types while classes are reference types. When a value type object is created, memory space will be allocated to store the value, thus its member variable cannot be null, whilst class member variables can be null. Hence, the compiler only complains when struct member variables are not assigned to.

Remember the thumb rule for Structs: All fields must be initialized. Values can be provided by you or default ones.

For Question 1:

When you initialize struct with 'new' (without parameters), all fields in it are initialized to default type values (0 for int, null for string etc). Since you are using parameterized constructor compiler does not use default one and hence you get error if you don't initialize field 'b'. You can still make this work as below:

public MyStruct(int a) : this()
{
   this.a = a;
}

For Question 2:

Recall the thumb rule I mentioned in the beginning. So you either use default constructor with 'new' initialization or set field values in calling code.

Quick suggestion: Please do not use public fields in class/struct. Use properties to encapsulate them.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM