Is there any way to use a type-parameter within an indexer declaration?
-
27-10-2019 - |
Question
I don't think so, but before I give up and use a method:
public T this<T>[String index]
{
get{
//return stuff
}
}
I don't have a type parameter in the class. I just want to return a different type based on what I want to get.
for example:
myObject<String>["SavedString"]
Is there a syntax for that? (I can't compile any of the code above, of course.)
Solution
No, properties can't be generic in C#. Nor can events, constructors, variables, operators or finalizers.
Basically there are generic types and generic methods, and that's it.
OTHER TIPS
Since properties can't be generic, the closest way you're going to get, is to do it like this:
public class SomeClass
{
public T GetValue<T>( string key )
{
// implement logic here
}
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow