简体   繁体   中英

Is it possible to call properties in constructor in C# so I don't have to write the validating check of the value twice?

I am studying Java and recently I started studying C# as well. In Java I was told to write the set method of some member of the class with a check to validate, for example if it is a String - the string not to be null. Then we call the set method in the constructor and when I initialize an object of the class using constructor it validates my data.

So in C# there are the so called properties which should be the same logic as set/get methods in Java and I can validate my data in the property.

How can I call that set method/set property in the constructor in C# so I don't have to write the validating code twice - once in the property and once in the constructor?

Code: Some simple example of class

class Program
{
    private int someVariable;

    public Program(int someVariable)
    {
        this.someVariable = someVariable;
    }

    public int SomeVariable
    {
        get { return someVariable; }
        set
        {
            if (value > 5)
            {
                Console.WriteLine("Error");
            }
            else
            {
                someVariable = value;
            }
        }
    }
    static void Main(string[] args)
    {
        Program pr = new Program(10);
        pr.SomeVariable = 10;
    }
}

You would call this.SomeVariable in your constructor which would then execute the set part of your property and validate the value. Right now, you are bypassing this by directly setting the variable someVariable value (at times called the 'backing field')

Usually in C#, I keep the backing field and the property next to each other so that it is easier to read the code, like this:

int _someVariable;
public int SomeVariable
{
    get { return _someVariable; }
    set { /* ... */ }
}

You can just access the property from your constructor:

public Program(int someVariable)
{
    SomeVariable = someVariable;
}

Note: You should probably not write directly to the console in your setter. A better way to do it would be to throw an exception -- that way the rest of your program can do something about it. Alternatively, you could just set a default value if the value passed in is out of range.

public int SomeVariable
{
    get { return someVariable; }
    set
    {
        if(value > 5)
            throw new InvalidOperationException("SomeVariable cannot be greater than 5.");
        someVariable = value;
    }
}

Or,

public int SomeVariable
{
    get { return someVariable; }
    set
    {
        someVariable = value > 5 ? 5 : value;
    }
}

just do it.

public Program(int someVariable)
{
    SomeVariable = someVariable;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM