John Smith
John Smith

Reputation: 233

Dynamic implementation of an Interface

Suppose I have an Interface with some properties:

public interface IDummy
{
    string First  {get;set;}
    string Second {get;set;}
    string Third  {get;set;}
    string Fourth {get;set;}
}

Now, I have a class which implements that interface:

public class DummyClass: IDummy
{
    // ...
}

Is it possible, not to implement the interface properties explicitly and instead use DynamicObject? For example:

public class DummyClass: DynamicObject, IDummy
{
    public override bool TryGetMember(GetMemberBinder binder, out object result)
    {
        // Get the value from a Config file or SQLite db or something
    }

    public override bool TrySetMember(SetMemberBinder binder, object value)
    {
        // Get the value to a Config file or SQLite db or something
    }
}

I am just curious if this is possible or not? Thanks.

Upvotes: 3

Views: 1902

Answers (3)

Markus Jarderot
Markus Jarderot

Reputation: 89241

You could make a wrapper.

class DummyWrapper : IDummy
{
    private readonly DynamicObject _wrapped;

    public DummyWrapper(DynamicObject wrapped)
    {
        _wrapped = wrapped;
    }

    string First
    {
        get { return _wrapped.First; }
        set { _wrapped.First = value; }
    }

    string Second
    {
        get { return _wrapped.Second; }
        set { _wrapped.Second = value; }
    }

    string Third
    {
        get { return _wrapped.Third; }
        set { _wrapped.Third = value; }
    }

    string Fourth
    {
        get { return _wrapped.Fourth; }
        set { _wrapped.Fourth = value; }
    }
}

You might also be interested in these questions:

Upvotes: 1

Marc Gravell
Marc Gravell

Reputation: 1064204

No, basically. An interface is for static typing; to satisfy an interface your type must actually provide a regular (non-dynamic) implementation. You could not claim to implement it (IDummy), and detect the names, but that could relate to any interface that uses those same names, not just IDummy.

Upvotes: 1

Oded
Oded

Reputation: 499382

No, this is not possible.

If you are implementing an interface, you need to implement all of its members. C# is still a statically typed language, after all.

When you say a type implements an interface, you are saying it conforms to its contract. Not implementing all of the members means that you are not complying with the contract.

The compiler would see your code and will not assume that you have implemented the contract correctly (in a dynamic fashion) - it will fail to compile.

Upvotes: 4

Related Questions