mikabuka
mikabuka

Reputation: 222

Forcing all class fields be initialized

Similar to struct in c#, that all fields in it must be initialized at compiling time, I'm interested to know if there is some way to obligate a programmer to initialize all the fields in a class and to have indication (error) while compiling a code.

Have a good day, Thanks.

Upvotes: 1

Views: 244

Answers (3)

Matthew Watson
Matthew Watson

Reputation: 109537

I really can't see the point of this, but:

You've already pointed out that a struct enforces this. Therefore you can do something like what you want by putting all the class's fields in a struct. Then if you add a new field to the struct, it will force you to add the field initialisation to the struct's constructor.

class Test
{
    public Test(int x, string y)
    {
        fields = new Fields(x, y);
    }

    public int X
    {
        get
        {
            return fields.X;
        }

        set
        {
            fields.X = value;
        }
    }

    public string Y
    {
        get
        {
            return fields.Y;
        }

        set
        {
            fields.Y = value;
        }
    }

    struct Fields
    {
        public Fields(int x, string y)
        {
            X = x;
            Y = y;
        }

        public int    X;
        public string Y;

        // Uncomment this and you get an error:
        // public double Z;
    }

    Fields fields;
}

This isn't really all that you want though - because you could still just add a field outside the struct. So I guess it doesn't really help a lot...

Upvotes: 2

ken2k
ken2k

Reputation: 48975

Providing a constructor that takes all properties as parameter, as NDJ said, is a good idea.

If you really want to get a warning or an error on compilation in case you forgot to update your constructor after adding a new property, you could build a custom Code Analysis rule (using the FxCop SDK) and check that every setter of public properties is called in the class constructor.

Upvotes: 3

NDJ
NDJ

Reputation: 5194

the easiest way is to provide a constructor which takes the fields you want to initialise - e.g.

public  class MyClass
{
     public string MyValue { get; set; }

     public MyClass(string myValue)
     {
         MyValue = myValue;
     }
}

Upvotes: 3

Related Questions