Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

c# How to define a same method in all the classes

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

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading