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.
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; }
}
}
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)
{
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With