Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

[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.

like image 922
Oliver Kane Avatar asked Mar 20 '23 02:03

Oliver Kane


2 Answers

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.

like image 61
StriplingWarrior Avatar answered May 03 '23 06:05

StriplingWarrior


You can't do this exactly as you have defined the question. The best way to tackle this is really to pull your factory out of the class completely:

public class BankAccount
{
}

public class SavingsAccount : BankAccount
{
}

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

Now the Factory has no dependency on the actual type. You can pass any derived class of BankAccount and get it back without doing any extra work or worrying about inheriting your factory method.

like image 43
Tim Copenhaver Avatar answered May 03 '23 06:05

Tim Copenhaver