1

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?

3
  • 2
    well have you tried it yourself? Commented Sep 28, 2022 at 15:02
  • 11
    The key here is static. Leave that out and yes, it would be a problem, and the compiler would complain. But a static is, storage-wise, part of the class, not the instance. Commented Sep 28, 2022 at 15:04
  • 3
    Consider int.MaxValue or DateTime.Now. They're both members of structs and they both have the same type as the struct. But neither of them will cause a cycle because one is a constant and the other is a static member and they're both accessed via the type name itself, not via an instance. Commented Sep 28, 2022 at 15:12

1 Answer 1

5

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.)
Sign up to request clarification or add additional context in comments.

2 Comments

"Syntactic sugar" is a fairly specific term, and so is "global variable". A static member is "somewhat like" a global variable in other languages, but there is no syntactic sugar involved -- there is no different or more elaborate way to write static declarations.
@JeroenMostert: You are right, it's not "syntactic sugar". I have rephrased it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.