how is it possible to know whether an object implements an indexer?, I need to share a logic for a DataRow and a IDataReader, but they don’t share any interface.
I tried also with generics but don’t know what restriction should I put on the where clause.
public class Indexer { // myObject should be a DataRow or a IDataReader private object myObject; public object MyObject { get { return myObject; } set { myObject = value; } } // won't compile, myObject has no indexer public object this[int index] { get { return myObject[index]; } set { myObject[index] = value; } } public Indexer(object myObject) { this.myObject = myObject; } } public class Caller { void Call() { DataRow row = null; IDataReader reader = null; var ind1 = new Indexer(row); var ind2 = new Indexer(reader); var val1 = ind1[0]; var val2 = ind1[0]; } }
You’d need to declare an interface with an indexer property, use that interface as the constraint, and the type argument class would need to implement that interface in order to satisfy the constraint.
As you don’t control the classes you want to use, that wouldn’t work.
An alternative is to make the
Indexerclass take the get/set operations as separate parameters:You could then do this: