I am wondering if there is an alternative to dot notation in C#. For instance, in Javascript, I can have an object like this:
const myObj = { foo: "bar" }
And then I can reference it like this:
let x = "foo";
let y = myObj[x]; //sets y = "bar"
Is this possible in C#? I have not found anything of the sort, but am wondering if there are alternatives that would function similarly.
You can implement an indexer in your class:
public class A
{
public int X { get; set; }
public string Y { get; set; }
public object this[string name]
{
get => GetType().GetProperty(name).GetValue(this, null);
set => GetType().GetProperty(name).SetValue(this, value);
}
}
Then use it:
var a = new A();
a["X"] = 10;
a["Y"] = "abc";
Console.WriteLine(a.X);
Console.WriteLine(a.Y);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With