Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fallback accessors in C#?

Tags:

c#

accessor

Does C# have anything like Python's __getattr__?

I have a class with many properties, and they all share the same accessor code. I would like to be able to drop the individual accessors entirely, just like in Python.

Here's what my code looks like now:

class Foo
{
    protected bool Get(string name, bool def)
    {
        try {
            return client.Get(name);
        } catch {
            return def;
        }
    }

    public bool Bar
    {
        get { return Get("bar", true); }
        set { client.Set("bar", value); }
    }

    public bool Baz
    {
        get { return Get("baz", false); }
        set { client.Set("baz", value); }
    }
}

And here's what I'd like:

class Foo
{
    public bool Get(string name)
    {
        try {
            return client.Get(name);
        } catch {
            // Look-up default value in hash table and return it
        }
    }

    public void Set(string name, object value)
    {
        client.Set(name, value)
    }
}

Is there any way to achieve this in C# without calling Get directly?

Thanks,

like image 812
Can Berk Güder Avatar asked May 30 '26 19:05

Can Berk Güder


2 Answers

No. Although C# supports reflection, it is read-only (for loaded assemblies). That means you can't change any methods, properties, or any other metadata. Although you could create a dynamic property, calling it wouldn't be very convenient - it would be even worse than using your Get method. Aside from using a Dictionary<string, object> and an indexer for your class, there's not much else you can do. Anyway, isn't doing a dictionary better if you have that many properties?

Python doesn't check if an attribute exists at "compile-time" (or at least load-time). C# does. That's a fundamental difference between the two languages. In Python you can do:

class my_class:
    pass

my_instance = my_class()
my_instance.my_attr = 1
print(my_instance.my_attr)

In C# you wouldn't be able to do that because C# actually checks if the name my_attr exists at compile-time.

like image 175
wj32 Avatar answered Jun 01 '26 09:06

wj32


I'm not sure, but perhaps the dynamic features of version 4.0 will help you with that. You'll have to wait though...

like image 28
R. Martinho Fernandes Avatar answered Jun 01 '26 09:06

R. Martinho Fernandes