Like isn't friends with Switch?



  • I write this design.

    public static void StartAllPool(Type t = null)
    {
    
    switch (t)
    {
        case typeof(Pool):
            StartPool();
            break;
        case null:
            break;
    }
    

    }

    t in Swich underlined red with error:

    The expression switch or operator case shall have a type of bool, char, string, integral, enum or type with a possible NULL value.

    But Type can contain null, then what's the problem?



  • "A corresponding type with possible null meaning" means Nullable<bool> / bool?Nullable<char> / char? and the rest Nullable<T> for the types listed in the communication by mistake.

    System.Type It's not on that list.

    In principle switch by Type or TypeCode is code smell, usually meaning that you should use objects instead of type + virtual functions, and the code should look like this:

    public static void StartAllPool(ISomeStartable startable) 
    {
        startable.Start();
    }
    

    or

    public static void StartAllPool(ISome some) 
    {
        this.Start(some.DoWork);
    }
    

    where ISomeStartable.Start() and ISome.DoWork() - methods specific to a particular type.




Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2