Reputation: 1869
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
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
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