Information Technology Reference
In-Depth Information
get { return ComputeValue(x, y); }
}
public int this [ int x, string name]
{
get { return ComputeValue(x, name); }
}
Notice that all indexers are declared with the this keyword. You cannot
name an indexer in C#. Therefore, every different indexer in a type must
have distinct parameter lists to avoid ambiguity. Almost all the capabilities
for properties apply to indexers. Indexers can be virtual or abstract; index-
ers can have separate access restrictions for setters and getters. You cannot
create implicit indexers as you can with properties.
This property functionality is all well and good, and it's a nice improve-
ment. But you might still be tempted to create an initial implementation
using data members and then replace the data members with properties
later when you need one of those benefits. That sounds like a reasonable
strategy—but it's wrong. Consider this portion of a class definition:
// using public data members, bad practice:
public class Customer
{
public string Name;
// remaining implementation omitted
}
It describes a customer, with a name. You can get or set the name using the
familiar member notation:
string name = customerOne.Name;
customerOne.Name = "This Company, Inc." ;
That's simple and straightforward. You are thinking that you could later
replace the Name data member with a property, and the code would keep
working without any change. Well, that's sort of true. Properties are meant
to look like data members when accessed. That's the purpose behind the
syntax. But properties are not data. A property access generates different
Microsoft Intermediate Language (MSIL) instructions than a data access.
Although properties and data members are source compatible, they are
not binary compatible. In the obvious case, this means that when you
 
Search WWH ::




Custom Search