Reputation: 1091
I have three different classes in my current project structured as below:
class BaseClass {
public string prop1;
public string prop2;
public string prop3;
}
class C1 : BaseClass {
public string prop3; // Common with class C2
public string prop4;
}
class C2 : BaseClass {
public string prop3; // Common with class C1
public string prop5;
}
I need to have an object which includes prop1, prop2, prop3, prop4, and prop5; but I don't want to have a duplication definition. I don't want to create a new class like this:
class NewClass {
public string prop1;
public string prop2;
public string prop3;
public string prop4;
public string prop5;
}
Is there a way (like interface, or abstract class, or anything else) that I can refactor my old classes into so that I can have an object with all 5 properties without defining a new class?
Upvotes: 1
Views: 2158
Reputation: 488
Will this help?
class BaseClass
{
public virtual string prop1 { get; set; }
public virtual string prop2 { get; set; }
public virtual string prop3 { get; set; }
public virtual string prop4 { get; set; }
public virtual string prop5 { get; set; }
}
class C1 : BaseClass
{
public override string prop4 { get; set; }
}
class C2 : BaseClass
{
public override string prop5 { get; set; }
}
Upvotes: 0
Reputation: 813
Definitely interfaces, just be aware that for matter of theory correctness, you would be implementing methods, not properties, a property is something different in C#. (Link: Properties in C#)
public interface IBaseClass
{
public string GetProperty1();
public string GetProperty2();
public string GetProperty3();
}
public interface IC1
{
public string GetProperty4();
}
public interface IC2
{
public string GetProperty5();
}
public class Implementation : IBaseClass, IC1, IC2
{
public string GetProperty1()
{
return "Value";
}
public string GetProperty2()
{
return "Value";
}
public string GetProperty3()
{
return "Value";
}
public string GetProperty4()
{
return "Value";
}
public string GetProperty5()
{
return "Value";
}
}
The benefit of doing it like this, is that the implementation class is forced to define such methods.
Upvotes: 0