lolotobg lolotobg - 3 months ago 18
C# Question

The modifier 'XXXX' is not valid for this item

Does anyone have an idea why I get these errors:

The modifier 'static' is not valid for this item

The modifier 'readonly' is not valid for this item


on line 7 of the following code:

using System;

namespace XXX
{
class YYY
{
private static readonly struct ZZZ
{
private int x = 0;
private int y = 0;
private int z = 0;
}
}
}


When I researched the matter, I found answers only for Interfaces which I am not very aware of but I only want to create a static readonly struct field in my class.

Answer

Static and readonly are both mmodifiers only used in the implementation of an object, not in the definition. When you declare the ZZZ struct object you will be using, at that point you can add the modifiers static and readonly.

using System;

namespace XXX
{
    class YYY
    {
        private struct ZZZ
        {
            private int x = 0;
            private int y = 0;
            private int z = 0;
        }

        private static readonly ZZZ myZZZ = new ZZZ(); //The declaration of a ZZZ instance.
    }
}