Philipp Lenssen
Philipp Lenssen

Reputation: 9218

C# pattern to pass what amounts to a subclass?

Given a virtually simulated tablet which launches apps like FooApp and BarApp which inherit from class App, what would be a good way to tell a function LaunchApp(...) which app to launch?

I'm currently passing LaunchApp(System.Type appType), where appType is e.g. typeof(FooApp), which then gets validated within the function. However, this pattern seems to lack proper type safety and passing autocompletion comfort. An alternative pattern on the other hand, where I use an Enum which then gets converted to the appType via e.g. switch-case, doesn't seem to adhere to D.R.Y. as I need to keep another redundant appType enum list. What would be a good pattern here?

Upvotes: 0

Views: 69

Answers (1)

Doh09
Doh09

Reputation: 2385

As I understand you wish for a different method to be called depending on the type of your object. But don't want to introduce a new enum to help make the decision of which method to call.

For this, i suggest you can use the type pattern working in newer C# versions. Where it casts your objects type and runs the switch case for that particular type.

https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/switch

Here is the example they use in the documentation.

private static void ShowCollectionInformation(object coll)
    {
        switch (coll)
        {
            case Array arr:
               Console.WriteLine($"An array with {arr.Length} elements.");
               break;
            case IEnumerable<int> ieInt:
               Console.WriteLine($"Average: {ieInt.Average(s => s)}");
               break;   
            case IList list:
               Console.WriteLine($"{list.Count} items");
               break;
            case IEnumerable ie:
               string result = "";
               foreach (var e in ie) 
                  result += "${e} ";
               Console.WriteLine(result);
               break;   
            case null:
               // Do nothing for a null.
               break;
            default:
               Console.WriteLine($"A instance of type {coll.GetType().Name}");
               break;   
        }
    }

Upvotes: 1

Related Questions