Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# generic method for multiple classes

I tried to search for solutions, but my problem is I don't even know what terms to use. Generics, Delegates, LINQ, Reflection, and Abstract ideas could be part of the solution, but my "Google-fu" isn't turning up the right answer.

Question: I have multiple classes (ClassA, ClassB, ClassC) that all have the same 2-3 properties DoThisA, DoThisB, DoThisC.

The way the code works is that I always want to do the same code to set DoThisA, DoThisB, and DoThisC when I process each of the classes.

For example, to simplify, the logic will always be:

{some computations to set string currentValueImProcessing to something}
if (xyz) [ClassA|B|C].DoThisA = currentValueImProcessing
else [ClassA|B|C].DoThisB = currentValueImProcessing

I don't want to write those same statements over and over, so how do I just send a reference to the class (A,B,C) to a method to do the logic?

If it was written correctly each of ClassA, ClassB, and ClassC would have implemented some generic class and I could use that, but I cannot. Each of the classes are independent but have the same named properties.

Any guidance on concepts/code?

Thanks!

like image 837
Adam Avatar asked Mar 29 '26 21:03

Adam


1 Answers

Create an interface for your properties:

internal interface IDoThis
{
    public string DoThisA { get; set; }
    public string DoThisB { get; set; }
    public string DoThisC { get; set; }
}

Then, make your classes implement it:

public class ClassA : IDoThis
{
    public string DoThisA { get; set; }
    public string DoThisB { get; set; }
    public string DoThisC { get; set; }
}

public class ClassB : IDoThis
{
    // Same properties
}

public class ClassC : IDoThis
{
    // Same properties
}

This, way, you'll be able to create a static initializer method somewhere:

internal static class MyClassesExtensions
{
    public static void InitTheStuff(this IDoThis obj)
    {
        // Do something here, for example:
        if (String.IsNullOrEmpty(obj.DoThisA))
            obj.DoThisA = "foo";
        else
            obj.DoThisB = obj.DoThisC;
    }
}

And then you can just call this.InitTheStuff() anywhere from ClassA, ClassB and ClassC.

like image 191
Lucas Trzesniewski Avatar answered Apr 01 '26 09:04

Lucas Trzesniewski



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!