How to implement an interface in a derived class or through partial classes?

I have a partial class created by a tool.

Foo.cs

public partial class Foo {
    [SomeAttribute()]
    public string Bar {get;set;}
}

I need to implement the following interface for Foowithout touching Foo.cs:

IFoo.cs

public interface IFoo {
    string Bar {get;set;}
}

An extension is Fooalso an option, but reusing a property is Barnot.

Can this be done?

+5
source share
3 answers

What prevents you from doing this again in another file?

public partial class Foo : IFoo
{
}

Since the property Baralready exists, it is not required to override it.

Or in a new class

public class FooExtended : Foo, IFoo
{
}

Again, you will not need to implement it Bar, since Foo already implements it.

+8
source

Foo, IFoo, Bar , .

Bar :

partial class Foo
{
    public string Bar { get; set; }
}

interface IFoo
{
    string Bar { get; set; }
}

partial class Foo : IFoo
{

}
+1

Since it Baris private, here is what you are looking for:

public partial class Foo : IFoo
{
    string IFoo.Bar
    {
        get
        {
            return this.Bar;  // Returns the private value of your existing Bar private field
        }
        set
        {
            this.Bar = value;
        }
    }
}

In any case, this is confusing and should be avoided if possible.

EDIT: Well, you changed your question, since it is Barnow publicly available, there is no longer a problem since Barit is always implemented in Foo.

+1
source

All Articles