Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dot Notation Alternatives

Tags:

c#

.net

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.

like image 652
GTrodd Avatar asked May 12 '26 15:05

GTrodd


1 Answers

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);
like image 150
Kirill Polishchuk Avatar answered May 15 '26 06:05

Kirill Polishchuk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!