structs

mp3909

Well-known member
Joined
Apr 22, 2018
Messages
61
Location
UK
Programming Experience
3-5
I just finished up reading on structs in C#.

I still do not understand why it is not possible to initialise instance fields in a struct but it is possible to initialise static fields?

To make my question clearer, why does this give an error:

C#:
using System;
namespace Sample
{
    struct Animal
    {
        private string name = "Adam";
    }
}


and this doesn't:

C#:
using System;
namespace Sample
{
    struct Animal
    {
        private static string name = "Adam";
    }
}
 
Structures are value types, as opposed to reference types (objects), their instance fields initialize to zero state with a default constructor.
If your struct needs a string field (an object) it should probably be defined as a class instead. (I only found only such struct in .Net Framework libraries, the Color struct has a name field/property that is type string, but for most colors that is not used.)
A static field does not belong to any instance, it belongs to the type.

Value Type Usage Guidelines | Microsoft Docs
Value Types | Microsoft Docs
Choosing Between Class and Struct | Microsoft Docs
static modifier - C# Reference | Microsoft Docs
 
Thank you for your reponse.
Yes, I know that structures are values types.
I also know that static fields do not belong to an instance.

But this still does not help me answer my question, why instance fields cannot be set to a value when declared?
 
Because of what I said: their instance fields initialize to zero state with a default constructor.
docs said:
The runtime inserts a constructor that initializes all the values to a zero state. This allows arrays of structs to be created without running the constructor on each instance.
 

Latest posts

Back
Top Bottom