views:

133

answers:

2

How can I create a parameterized properties in C#.

public readonly string ConnectionString(string ConnectionName)
{
    get { return System.Configuration.ConfigurationManager.ConnectionStrings[ConnectionName].ToString(); }
}
+10  A: 

The only type of parameterized property you can create in C# is an indexer property:

public class MyConnectionStrings
{
    private string GetConnectionString(string connectionName) { ... }

    public string this[string connectionName]
    {
        get { return GetConnectionString(connectionName); }
    }
}

Otherwise, just create a method instead - that seems to be closer to what you are looking for.

Aaronaught
What is the use of indexer then ?
Shantanu Gupta
@Shantanu: Think of `Dictionary<TKey, TValue>`. To get a specific value, you write `var value = dictionary[key]`. That's an index property. It's not much more than a method wrapper, but then again, so are all properties.
Aaronaught
Thx for putting light on it.
Shantanu Gupta
A: 

C# 4 allows this, but only to access external COM properties..

Matthew Flaschen