Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling subclass constructor from static base class method

Ok... in Objective C you can new up a subclass from a static method in the base class with 'new this()' because in a static method, 'this' refers to the class, not the instance. That was a pretty damn cool find when I first found it and I've used it often.

However, in C# that doesn't work. Damn!

So... anyone know how I can 'new' up a subclass from within a static base class method?

Something like this...

public class MyBaseClass{

    string name;

    public static Object GimmeOne(string name){

     // What would I replace 'this' with in C#?
        return new this(name); 

    }

    public MyBaseClass(string name){
        this.name = name;
    }

}

// No need to write redundant constructors
   public class SubClass1 : MyBaseClass{ }
   public class SubClass2 : MyBaseClass{ }
   public class SubClass3 : MyBaseClass{ }

SubClass1 foo = SubClass1.GimmeOne("I am Foo");

And yes, I know I can (and normally would) just use the constructors directly, but we have a specific need to call a shared member on the base class so that's why I'm asking. Again, Objective C let's me do this. Hoping C# does too.

So... any takers?

like image 259
Mark A. Donohoe Avatar asked Nov 19 '25 21:11

Mark A. Donohoe


1 Answers

C# doesn't have any exact equivalent to that. However, you could potentially get around this by using generic type constraints like this:

public class MyBaseClass
{
    public string Name { get; private set; }

    public static T GimmeOne<T>(string name) where T : MyBaseClass, new()
    {
        return new T() { Name = name };
    }

    protected MyBaseClass()
    {
    }

    protected MyBaseClass(string name)
    {
        this.Name = name;
    }
}

The new() constraint says there is a parameterless constructor - which your didn't but we make it private to hide that from consumers. Then it could be invoked like this:

var foo = SubClass1.GimmeOne<SubClass1>("I am Foo");
like image 96
Steve Michelotti Avatar answered Nov 22 '25 12:11

Steve Michelotti



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!