mardi 18 février 2020

avoid magic strings in c# [duplicate]

I have this extension method in order to retrieve the validation error message of a property:

public static string GetValiAttriError(this object instance, string propertyName)
{
    var attrType = typeof(ValidationAttribute);
    var property = instance.GetType().GetProperty(propertyName);
    var r = (ValidationAttribute)property.GetCustomAttributes(attrType, false).First();
    return r.ErrorMessage;
}

and this is how I call it:

UserForReg userForRegi = new UserForReg();
var errorMessage = userForReg.GetValiAttriError("PropertyName");

Instead of having to use a magic string like in this case "PropertyName" for the name of the property I could love to have a typed solution to avoid error during execution when the name of a property changes.

Something linke this would be wonderful (without even the need of an instance of UserForReg):

var errorMessage = GetValiAttriError(UserForReg.PropertyName);

Is it possible?





Aucun commentaire:

Enregistrer un commentaire