How to solve System.InvalidCastException: Unable to cast object of type `x` to object of type `y`
10:05 26 Sep 2026

Example to reproduce the issue:

    public interface INonJunctionEntity
    {
        public string? EnglishName { get; set; }
    }


    public abstract class NonJunctionEntity : INonJunctionEntity
        where T : NonJunctionEntity
    {
        public string? EnglishName { get; set; }

        // other code to be shared between classes that extends  NonJunctionEntity


    }
 
 public class Category: NonJunctionEntity
   {

         // properties and  navigation properties..... 

   }

public class Program{

     static void Main(string[] args)
    {
        List x =X();
        List y=  (List)(object)data; // faulty line.
    }

    public List X(){
              //code.....
    }

     
}

faulty line throws the following error:

17:32:36:986    System.InvalidCastException: Unable to cast object of type 'System.Collections.Generic.List`1[INonJunctionEntity]' to type 'System.Collections.Generic.List`1[Category]'.

https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/types/casting-and-type-conversions:

Type conversion exceptions at run time

In some reference type conversions, the compiler can't determine whether a cast is valid. It's possible for a cast operation that compiles correctly to fail at run time. As shown in the following example, a type cast that fails at run time causes an InvalidCastException to be thrown.

C#

Animal a = new Mammal();
Reptile r = (Reptile)a; // InvalidCastException at run time

That described the problem, not the solution, I still need to perform casting from INonJunctionEntity to it's child Category , how to do it?

c# asp.net-core interface casting