Possible Duplicate:
How do I overload the square-bracket operator in C#?
For a class is it possible to overload the operator [] in C#?
If so what is the correct syntax to declare the [] overloaded function?
Also can the operator [] returns different data types based off the parameter given? If not, what do you think is my other solution? Should I use Object instead?
public class MyClass {
private Dictionary<string,Element> eAttribs;
private Dictionary<string,string> defAttribs;
// Also can the operator [] returns different data types based off the parameter given?
// If not, what do you think is my other solution?
public Element operator[](string attribKey) {
if (eAttribs.containsKey(attribKey)
return eAttribs[attribKey];
else return null;
}
// COMPILE Error below: Unexpected symbol '['
public string operator[](string attribKey) {
if (defAttribs.containsKey(attribKey)
return defAttribs[attribKey];
else return null;
}
}
In c# these are called indexers.
Syntax:
You can return only one object. Use a base class instead for all the type objects you have to return.