Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does IDataErrorInfo.this[string propertyName] work in C#?

I've always implemented the IDataErrorInfo interface without actually wondering what this line means and how it works.

string IDataErrorInfo.this[string propertyName]
{
    get { return this.GetValidationError(propertyName); }
}

How does .this[string propertyName] work, and when/how does this property get called?

like image 750
Rachel Avatar asked Jun 21 '13 13:06

Rachel


1 Answers

This is explicit interface implementation of an indexer. (EDIT: The IDatatErrorInfo. part of the signature signifies the explicit interface implementation, and the .this[...] part signifies an indexer.)

It would be called whenever you have an explicitly typed IDataErrorInfo object and you use square brackets on it to retrieve/get a value while passing a string in. For example:

IDataErrorInfo myDataErrorInfo = GetErrorInfo();
string myPropertyError = myDataErrorInfo["SomePropertyName"];

Note that since it's an explicit interface implementation, it will only be accessible when the type is known exactly as an IDataErrorInfo. If you have it typed as your subclass, it won't be accessible unless that class exposes it:

MyDataErrorInfoImpl myDataErrorInfo = GetErrorInfo();
string myPropertyError = myDataErrorInfo["SomePropertyName"]; //compiler error!
like image 153
Chris Sinclair Avatar answered Sep 23 '22 14:09

Chris Sinclair