In implementing IDataErrorInfo the following code compiles and works without a problem:
public string Error
{
get { return null; }
}
public string this[string columnName]
{
get
{
switch (columnName)
{
case "MemberId": return validate(MemberId, 0, RegexLibrary.NonEmptyRegex);
case "PolicyType": return validate(PolicyType, 1, RegexLibrary.NonEmptyRegex);
case "EffectiveDateFrom": return validate(EffectiveDateFrom, 2, RegexLibrary.DateRegex);
case "EffectiveDateTo": return validate(EffectiveDateTo, 3, RegexLibrary.DateRegex);
case "Phone": return validate(Phone, 4, RegexLibrary.PhoneRegex);
case "CompanyName": return validate(CompanyName, 5, RegexLibrary.NonEmptyRegex);
}
// string.Empty is no error.
return string.Empty;
}
}
public string validate(string column, int position, string regex)
{
string invalid = string.Format("{0} is invalid.", column);
if (column == null)
{
SetErrorStatus(1, position);
return invalid;
}
Match match = Regex.Match(column, regex);
if (!match.Success)
{
SetErrorStatus(1, position);
return invalid;
}
SetErrorStatus(0, position);
return string.Empty;
}
However, If validate(...) is defined as a function like so:
Func<string, int, string, string> validate = (column, position, regex) =>
{
string invalid = string.Format("{0} is invalid.", column);
if (column == null)
{
SetErrorStatus(1, position);
return invalid;
}
Match match = Regex.Match(column, regex);
if (!match.Success)
{
SetErrorStatus(1, position);
return invalid;
}
SetErrorStatus(0, position);
return string.Empty;
};
The compiler defines the validate(...) func as static. Why?
TIA
In that case, validate
is not a method but a field. The field is an instance member. The object assigned to that field is a delegate that refers to an anonymous method. There's no reason for that method to be an instance member because it doesn't make any reference to the current instance. So, you have an instance field referring to a static method.