Assuming that it's not always an int
you want (if it is, then why isn't it a Dictionary<string, int>
?) - I think something like this works and gets pretty close:
int i = @int["Key"];
string s = @string["Key"];
object o = @object["Key"];
This combines the fact that identifiers can be prefixed with @
(it's usually optional, but it's required if your identifier is a reserved keyword, like int or string) with the default indexed parameter from Andrew Hare's answer.
It does require another class to be used to get the indexing - though if you wanted to use parens instead of square brackets for the key name, you could use methods instead:
int i = @value<int>("Key");
Implementation would be something like:
class DerivedClass : BaseClass {
void Main() {
int i = @int["Key"];
}
}
abstract class BaseClass {
private Dictionary<string, string> D { get; set; }
protected Indexer<int> @int = new Indexer<int>(s => int.Parse(s), this);
protected Indexer<string> @string = new Indexer<string>(s => s, this);
protected Indexer<object> @object = new Indexer<object>(s => (object)s, this);
protected class Indexer<T> {
public T this[string key] {
get { return this.Convert(this.BaseClass.D[key]); }
}
private T Convert(string value) { get; set; }
private BaseClass { get; set; }
public Indexer(Func<T, string> c, BaseClass b) {
this.Convert = c;
this.BaseClass = b;
}
}
}
Or, the method route:
class DerivedClass : BaseClass {
void Main() {
int i = @value<int>("key");
}
}
abstract class BaseClass {
private Dictionary<string, string> D { get; set; }
protected T @value<T>(string key) {
string s = this.D[s];
return Convert.ChangeType(s, typeof(T));
}
}
After reading through the language spec - if you're not tied to @
, _
is a legal identifier. Combine that with indexers and you get:
int i = _["key"];