Search code examples
c#genericsuser-defined-types

Generic Methods with user defined types


Scenario I am facing is I have a base class

public class BaseClass
{
    public string SomeVal { get; set; }
    public BaseClass(string someVal)
    {
        this.SomeVal = someVal;
    }
}

and two other classes that inherit from BaseClass using the constructor from BaseClass

public class ClassA : BaseClass
{
    public ClassA(string someVal) : base (someVal)
        {
        }
}

and

public class ClassB : BaseClass
{
    public ClassB(string someVal) : base (someVal)
        {
        }
}

I'd like to create a generic method that can take either ClassA types or ClassB types to modify the SomeVal value. I have tried doing this

public static void func<T>(T className)
{
    className.SomeVal = "Hello World";
}

but obviously the compiler doesn't know what SomeVal is, I have also tried public class ClassA<T> : BaseClass but still at the same point of it not knowing what SomeVal is, additionally, all uses of ClassA in the code no longer work with the error Using the generic type 'ClassA<T>' requires 1 type arguments

I have also considered overloads for the functionality I require, but that can get tedious for my scenario as I have multiple classes that inherit from BaseClass, and the method I would be creating isn't a big one either


Solution

  • You can constrain T to BaseClass

    public static void func<T>(T className)
       where T : BaseClass
    

    If you aren't doing much with T, I would consider making func not generic and just take a BaseClass

    public static void func(BaseClass className)