NotARobot
NotARobot

Reputation: 978

Override abstract interface property

Say I have a class like...

public abstract class Base
{
    public abstract IAttributes Attributes{ get; set; }
}

public interface IAttributes
{
    string GlobalId { get; set; }
}

And a class like this...

public class ImplementAttributes : IAttributes
{
    public string GlobalId { get; set; } = "";
    public string LocalId { get; set; } = "";
    // Other Properties and Methods....
}

And then I implement it like...

public class Derived: Base
{
    public new ImplementAttributes Attributes { get; set; } 
}

Now, I realise the above will not work because I can't override the property Attributes and if I hide it with new then the following bellow is null because the Base property does not get written.

public void DoSomethingWithAttributes(Base base)
{
    var Foo = FindFoo(base.Attributes.GlobalId);  // Null because its hidden
}

But I would like to be able to access the Base and Derived property attributes eventually like Above.

Can this be accomplished? Is there a better way?

Upvotes: 0

Views: 1311

Answers (1)

Blorgbeard
Blorgbeard

Reputation: 103467

You can use generics:

public abstract class Base<T> where T: IAttributes
{
    public abstract T Attributes{ get; set; }
}

public interface IAttributes
{
    string GlobalId { get; set; }
}

And

public class Derived: Base<ImplementAttributes>
{
    public override ImplementAttributes Attributes { get; set; } 
}

And then:

public void DoSomethingWithAttributes<T>(Base<T> b) where T : IAttributes
{
    var Foo = FindFoo(b.Attributes.GlobalId);
}

You can pass Derived instances without specifying a type parameter explicitly:

Derived d = new Derived();
DoSomethingWithAttributes(d);

Upvotes: 2

Related Questions