Home > database >  Change value of property depending another in class
Change value of property depending another in class

Time:01-07

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?

CodePudding user response:


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

CodePudding user response:

As an answer is already posted and accepted, I just want to point to a different thing.

  • Never implement this type of mechanism in a class! Keep classes as simple as possible.
  • Please use classes as POCOs, and implement this type of logic in a different layer of the application (e.g. Business Logic layer).

Otherwise, over time, your application will become complex and convoluted and hence hard to maintain.

  •  Tags:  
  • c#
  • Related