Is it object?
Pretty much. There is no common interface or class you can use, so object
is really the only thing guaranteed shared in the hierarchy.
What if the indexed object does not derive from object?
This is not possible in .NET. System.Object
is the base type of all types, and values can always be treated as an object (even if they do require boxing for this to work).
However, passing in as object
will not provide access to the indexer, other than via reflection.
The only direct way to do this would be via dynamic
, but that requires .NET 4 (and is not type safe, which means you could get runtime exceptions).
A better approach might be to provide a Func<T, int, string>
which would allow you to, at the call site, specify how to extract the value:
void DoSomething<T>(T object, Func<T, int, string> valueExtractor)
{
string foo = valueExtractor(object, 0);
}
Then call via:
DoSomething(indexedObject, (o,i) => o[i].ToString());
This allows you to pass in an object and a mechanism to extract a value given an index at the call site, which works for any type.
Edit in regards to:
Edit: I am looking for some contract enforcement that causes callers to pass objects that implement said indexer.
There is not a built in contract or interface that these types both implement, nor any way to constrain a generic based on the existence of an indexer. You will need a different approach, such as my suggestion of using a delegate to extract the value.