Sparkette
Sparkette

Reputation: 1869

How to always call constructor of current class, even in a derived class?

If I run the following C# code, it only outputs BaseClass() called, which is understandable. However, what if I wanted BaseClass.CreateInstance() to always return an instance of the class it's being called on, even if that's actually a different class that inherits that method?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Example
{
    class BaseClass
    {
        public BaseClass()
        {
            Console.WriteLine("BaseClass() called");
        }

        public static BaseClass CreateInstance()
        {
            return new BaseClass();
        }
    }

    class DerivedClass : BaseClass
    {
        public DerivedClass()
            : base()
        {
            Console.WriteLine("DerivedClass() called");
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            DerivedClass.CreateInstance();
            Console.ReadLine(); //pause so output is readable
        }
    }
}

Upvotes: 1

Views: 75

Answers (2)

Reed Copsey
Reed Copsey

Reputation: 564471

You're actually not calling it on DerivedClass. The compiler sees that there is a static method on BaseClass (and not DerivedClass) and automatically converts that into a call to BaseClass.CreateInstance.

One option would be to use generics to handle this:

public static T CreateInstance<T>() where T : BaseClass, new()
{
    return new T();
}

This would allow you to write:

DerivedClass dc = BaseClass.CreateInstance<DerivedClass>();

Upvotes: 3

Matthew
Matthew

Reputation: 25773

You're not creating an instance of DerivedClass in your CreateInstance method, so you're not getting one back, hence it's constructor is not called.

If you were to do var bla = new DerivedClass() it would call its constructor.

Upvotes: 0

Related Questions