C# How to make a factory method return of the subclass type

c#

Solution

Make it recursively generic:

public class BankAccount<T> where T : BankAccount<T>, new()
{
    public T SomeFactoryMethod() { return new T(); }
}

public class SavingsAccount: BankAccount<SavingsAccount>{}

You'll note that I made the factory method non-static, because static methods aren't inherited.

Problem

[MAJOR EDITS, my first post was somewhat misleading. My appologies] Given a class such as: ``` public class DatabaseResult{ public bool Successful; public string ErrorMessage; //Database operation failed public static DatabaseResult Failed(string message) { return new DatabaseResult{ Successful = true, ErrorMessage = message }; } } ``` How can I implement subclasses such that I can add additional properties to represent data relevant to the particular operation (such as MatchedResult in the case of a SELECT type query) without the need to implement that static failure function? If I try to use plain inheritance, the return type will be of the parent class. Eg: ``` DoThingDatabaseResult : DatabaseResult { public IEnumerable<object> SomeResultSet; public static Successful(IEnumerable<object> theResults){ return new DoThingDatabaseResult { Successful = true, ErrorMessage = "", SomeResultSet = theResults }; } //public static DatabaseResult Failed exists, but it's the parent type! } ``` The goal is to avoid needing to copy the Failed static function for every subclass implementation.

Original source

Related problems