Conrad Clark
Conrad Clark

Reputation: 4526

Is there any way to use a type-parameter within an indexer declaration?

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.)

Upvotes: 0

Views: 145

Answers (2)

Frederik Gheysels
Frederik Gheysels

Reputation: 56934

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
    }
}

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1500785

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.

Upvotes: 3

Related Questions