Anand
Anand

Reputation: 165

Need to add same properties in two different classes

I have two classes like Class A and Class B. Class A have some properties, methods and Class B have only the properties. But both Classes have the same set of properties.

My Question is, If I add any new property in Class A, I need to add that in Class B also. If I did not add means, need to show error. How can I achieve this through C#?

Upvotes: 2

Views: 2933

Answers (3)

Safwan Shaikh
Safwan Shaikh

Reputation: 546

You can go with the abstract class. The abstract keyword enables you to create classes and class members that are incomplete and must be implemented in a derived class.

Here is a simple example related to your question However you can understand and learn about Abstract classes here : Abstract Class

using System;

public class Program
{
    public static void Main()
    {
        A objA = new A();
        objA.printA();
        B objB = new B();
        objB.printB();

    }
}

abstract class Parent{

    public int a = 5;

}

class A : Parent
{
    public void printA()
    {
        Console.WriteLine("In class A, value is "+a);
    }
}

class B : Parent
{
    public void printB()
    {
        Console.WriteLine("In class B, value is "+a);
    }
}

Output of the above program is:

In class A, vlaue is 5
In class B, vlaue is 5

Hope this helps you.

Upvotes: 2

Antoine V
Antoine V

Reputation: 7204

Or you can use keyword abstract to create a class in common for A and B.

abstract class BaseClass   // Abstract class
{
    public int X {get;set;} // property in common for 2 class
}

class A : BaseClass
{
}

class B : BaseClass
{
    public int Y {get;set;} // other property of B
}

Upvotes: 2

tomsky
tomsky

Reputation: 545

You may achieve this by using an Interface and implementing it both in class A and class B. In the interface, define the property that is required in class A and B:

public interface ICommonProperty
{
   string MyProperty{ get; set; }
}

Upvotes: 7

Related Questions