Search code examples
c#wpfidataerrorinfo

IDataErrorInfo reduce redundancy


A code contains some redundant data how do i remove redundancy and simplify my code without changing its functionality..

Also i wanted to know the right way of implementing IDataErrorInfo

public string Error and public string this[string columnName] both property does the work of checking null values i dont want both to check for nulls.


Solution

  • In general it's better to use validation attributes for that, but if speak about your concrete example - you can remove redundancy like this:

    public string Error
    {
        get { return this[null]; }
    }
    
    public string this[string columnName]
    {
        get
        {                    
            if (columnName == null || columnName == "UnitCode") {
                if (String.IsNullOrEmpty(UnitCode)) {
                    return "Unit Code cannot be empty";
                }
            }
            if (columnName == null || columnName == "UnitName") {
                if (string.IsNullOrEmpty(UnitName)) {
                    return "Unit Name cannot be Empty";
                }
            }
            return null;
        }
    }