Home > Software design >  Is there a way to incorporate multiple inheritance for one generic parameter that is the same for tw
Is there a way to incorporate multiple inheritance for one generic parameter that is the same for tw

Time:03-09

The two generic parameters are the same, but I have two different methods that use two different generic parameter type constraints. I am trying to simplify the amount of code by using generics.


public static void thisClass.MainMethod<T1, T2>() where T1 : Control where T2 : TextBoxBase
{
    thisClass.FirstMethod<T1>(object x);  // where T : Control is needed for ((T)x).OneMethod();
    thisClass.SecondMethod<T2>(object x); // where T : TextBoxBase is needed for ((T)x).TwoMethod();
}

The class is a static class that holds all of the methods. Is there a way to simplify it to the following?

public static void thisClass.MainMethod<T1>(object control) where T1 : Control, TextBoxBase
{
    thisClass.FirstMethod<T1>(object objControl);
    thisClass.SecondMethod<T1>(object objControl);
    //more code here
}

EDIT: Here what FirstMethod and SecondMethod looks like, in case it helps.

public static void FirstMethod<T1>(object objControl) where T : Control
{
    //some code here
    string someStringVariableNeededInThisMethod = ((T1)objControl).Text; //not just this specific method needs to be called
    //more code here
}

public static void SecondMethod<T1>(object objControl) where T : TextBoxBase
{
    //some code here
    ((T1)objControl).AcceptsTab() = true; //not just this specific method needs to be called
    //more code here
}

CodePudding user response:

C# automatically treats objects of derived classes as if they are an instance of the base class as well. In fact, in this case, you don't need generics at all.

The following is an example of this. Think of Base as Control and Derived as TextBoxBase (which inherits from Control):

using System;

namespace ConsoleApp3
{
    public class Base
    {
        public int BaseInt { get; private set; } = 0;
        public void IncrementBaseInt() => BaseInt  ;
    }

    public class Derived : Base
    {
        public void PrintBaseInt() => Console.WriteLine($"{BaseInt}");
    }

    public static class Foo
    {
        
        public static void BaseMethod(Base argument) => argument.IncrementBaseInt();
        
        public static void DerivedMethod(Derived argument) => argument.PrintBaseInt();

        public static void Method(Derived argument) 
        {
            DerivedMethod(argument);
            BaseMethod(argument);
            DerivedMethod(argument);
        }
    }

    internal class Program
    {
        static void Main(string[] args)
        {
            Derived derivedArgument = new ();
            Foo.Method(derivedArgument);
        }
    }
}

This program prints out 0 then 1. But notice I could have written the signature of BaseMethod with Derived as the argument type and it would do exactly the same thing.

  • Related