demis15
demis15

Reputation: 51

Inheritance of Properties in C#

How to prevent inheritance of a property, so that it is no longer counted in the instantiated object. In the following example, I want object instance B to contain just two properties, namely MyCommonProperty and Name.

Properties must remain public

public class A
{
    public string MyCommonProperty { get; set; }
    public string MyClassASpecificProperty { get; set; }
}
public class B : A
{   
    public string Name { get; set; }    
}

Upvotes: 0

Views: 1093

Answers (4)

nrmontagne
nrmontagne

Reputation: 151

In the same line as Mathieu Guindon suggested, you could use explicit interface implementation to "hide" the property, but I don't see it be a good idea. The trickery would go as follow:

public interface IFoo
{
    public string MyCommonProperty { get; set; }
    public string MyClassASpecificProperty { get; set; }
}

public class A : IFoo
{
    public string MyCommonProperty { get; set; }
    string string MyClassASpecificProperty { get; set; }
}

public class B : IFoo
{
    public string MyCommonProperty { get; set; }
    public string Name{ get; set; }

    string IFoo.MyClassASpecificProperty { get; set;}
}

Upvotes: 1

Mathieu Guindon
Mathieu Guindon

Reputation: 71227

Don't use inheritance when inheritance isn't applicable. Two unrelated classes can still have a common interface without inheritance if you specify an explicit interface:

public interface ICommonThings
{
    string SomeProperty { get; set; }
}

public class Thing1 : ICommonThings
{
    public string Thing1Stuff { get; set; }
    public string SomeProperty { get; set; }
}

public class Thing2 : ICommonThings
{
    public string Thing2Stuff { get; set; }
    public string SomeProperty { get; set; }
}

Upvotes: 1

Carlo Capuano
Carlo Capuano

Reputation: 392

you can't, but you can:

create a Base Class X with only "MyCommonProperty" and have both A and B inherit from it adding their property.

or

"MyCommonProperty" is actually in a interface which both class implement

Upvotes: 3

jnap
jnap

Reputation: 84

Change the modifier of the properties you don't want inherited types to access to private.

Upvotes: 4

Related Questions