Home > Software engineering >  How to define a same method in all the classes
How to define a same method in all the classes

Time:11-18

public class Inputs
{
    public string firstname { get; set; }
    public string lastname { get; set; }
}

public class Data
{
    public class D1 : Inputs { }
    public class D2 : Inputs { }
    public class D3 : Inputs { }
}

Data.D1 d1 = new Data.D1();
d1.firstname = "first";

Data.D2 d2 = new Data.D2();
d2.firstname = "first";

Data.D3 d3 = new Data.D3();
d3.firstname = "first";

I have 100 classes in Data form D1 to D100 is there a way to skip writing the same code for all 100 classes

CodePudding user response:

you should explore Abstract class, Base class or Virtual methods in C#.

There are many ways to solve this issue. But again it depends on the requirement.

you can use the Abstract class if you want the implementation in one class and derived classes should use the same implementation.

public abstract class Inputs
{
    public string firstname { get; set; }
    public string lastname { get; set; }

    public void SomeMethod()
    {
        Console.WriteLine("SomeMethod");
    }
}

One way is to just inherit from a Base class and just implement the method in the base class.

Another way is to use virtual with the method and override in the child class if you want to override the base class method implementation.

public virtual void SomeMethod()
{
    Console.WriteLine("SomeMethod");
}

I would suggest you read Object Oriented Programming concepts like Inheritance, Abstraction, and Polymorphism.

Note: But you have a really bad design of your application, It's not good practise to have 100 classes for the exact same functionality. Although my above answer can help you. But you have to revisit and start redesigning your application. This is not going to help in future.

CodePudding user response:

Since you mentioned „countries“ I believe you are looking for a way to initialize the data, since the data of the countries may be static and won’t change.

Consider this:

public class Inputs
{
    public string firstname { get; }
    public string lastname { get; }
}

public class Data
{
    public class D1 : Inputs
    { 
        public D1()
        {
            firstName = "first";
        }
    }
}
  •  Tags:  
  • c#
  • Related