Home > Net >  Struct within struct C#
Struct within struct C#

Time:09-29

While studying C# , I came across the following piece of code:

public struct position
{
    public static readonly position Zero;
    public double x;
    public double y;
    ...
}

It's not the whole code, but this is the part I need help understanding. Wouldn't creating a instance of the struct inside the struct create a infinite loop?

CodePudding user response:

Wouldn't creating a instance of the struct inside the struct create a infinite loop?

Indeed, and if you remove the static keyword, you actually get the following error message:

Struct member 'position.Zero' of type 'position' causes a cycle in the struct layout

So, why does static "fix" the problem? Because static members are not stored per instance of the struct. Instead, static members are something akin to a "global variable" in C#.

Thus, in your example,

  • a position is defined by its x, y, etc. values. These are the values that "take up space" when you declare a new instance of your struct.
  • In addition, there is a special "constant" postition.zero, containing a position with all its values set to the default value. (I put "constant" in quotes, since it's technically not a C# constant, but it behaves similarly to one, since it's readonly.)
  •  Tags:  
  • c#
  • Related