Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Change value of property depending another in class

I have a class named ValidationsResult with this properties:

public class ValidationsResult
{
    public bool IsValid { get; set; }        

    public string[] Errors { get; set; }

    public void AddError(string error)
    {
        Errors.Append(error);
    }
}

But I want that the property IsValid to be read only, and depending if the object has Errors or not modify that property automatically.

How can I do that?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :


public class ValidationsResult
{
    public bool IsValid { get => Errors != null && Errors.Length == 0; }  // no errors = valid      

    public string[] Errors { get; set; }

    public void AddError(string error)
    {
        Errors.Append(error);
    }
}

That will make it readonly and it will tell you if you have errors

Based on the comment, yes. Better if you designed it in the following fashion.


public class ValidationsResult
{
    public bool IsValid { get => Errors.Count == 0; }  // or !Errors.Any()      

    public List<string> Errors { get; } = new List<string>();

    public void AddError(string error)
    {
        Errors.Add(error);
    }
}

You initialize the errors but outside consumer can still use it. Hence – next evolution


public class ValidationsResult
{
    private List<string> _errors  = new List<string>(); // private member

    public bool IsValid { get => _errors.Count == 0; }  // or !Errors.Any()      

    public string[] Errors { get => _errors.ToArray(); }

    public void AddError(string error)
    {
        _errors.Add(error);
    }
}

Now you encapsulating your error collection not letting consumer to modify it directly, but via AddError

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading