Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

An expression of type ... cannot be handled by a pattern when class is sealed

I am getting a rather strange error:

CS8121 An expression of type 'IGrouping<string, IMyInterface>' cannot be handled by a pattern of type 'MyClass1'.

The error is occuring on the line:

if(tGroup is MyClass1 myclass1)

However, no error is provided for MyClass2 which is not sealed.

  1. What is causing this?
  2. Other than not sealing MyClass1 what solutions are there?

using System;
using System.Collections.Generic;
using System.Linq;

namespace Demo
{

    class Program
    {

        static void Main()
        {

            IEnumerable<IMyInterface> myInterfaces = new List<IMyInterface>();
            foreach (IGrouping<String, IMyInterface> tGroup in myInterfaces.GroupBy(x => x.XXX))
            {
                if(tGroup is MyClass1 myclass1)
                {
                }
                if(tGroup is MyClass2 myClass2)
                {
                }
            }

        }

    }

    public interface IMyInterface 
    {
        String XXX { get; } 
    }

    public sealed class MyClass1 : IMyInterface
    {
        public String XXX { get; }
    }

    public class MyClass2 : IMyInterface
    {
        public String XXX { get; }
    }

}
like image 247
Harry Will Avatar asked Nov 30 '25 06:11

Harry Will


1 Answers

If MyClass is sealed, then there will never be a subclass that inherits MyClass and implements IGrouping<string, IMyInterface> The compiler is smart enough to deduce that, and hence "complains".

If it is not sealed there could be something like this:

class WhatEver : MyClass, IGrouping<string, IMyInterface> { ... }

So the compile cannot rule out if the is will ever succeed.

edit I bellieve, what you actually want to do is something like this:

foreach (IGrouping<String, IMyInterface> tGroup in myInterfaces.GroupBy(x => x.XXX))
{
    foreach(IMyInterface item in tGroup)
    {
        if(item is MyClass1 myclass1)
        {
        }
        if(item is MyClass2 myClass2)
        {
        }
    }
}
like image 189
CSharpie Avatar answered Dec 01 '25 19:12

CSharpie