0

Why is the compiler saying it cannot cast a generic type to object? I thought all objects were convertible to object. Is this possible?

https://dotnetfiddle.net/jFW4d0

using System;
                    
public class Program
{
    public abstract class Specification<T> where T : class
    {
        public abstract bool IsSatisfiedBy(T entity);
        
        public Specification<object> ToObject() {
            return (Specification<object>)this; // Compilation error (line 10, col 11): Cannot convert type 'Program.Specification<T>' to 'Program.Specification<object>'
        }
    }
    
    public static void Main()
    {
        Console.WriteLine("Hello World");
    }
}
TugboatCaptain
  • 4,150
  • 3
  • 47
  • 79

2 Answers2

1

Specification<T> is a type. Specification<object> is another different type. The code is attempting to cast a Specification<T> to a Specification<object>

  • this is the cast that the compiler is referring to
  • this cast is not the same as casting T to object
Phillip Ngan
  • 15,482
  • 8
  • 63
  • 79
0

If you absolutely have to have this functionality, your best bet it to create a new Specification, set that object, and return it. However, since Specification is abstract, you obviously cannot do that work in this class - it must be implemented on each subclass.

If you share more of the use case behind this method, perhaps I can recommend a better approach overall.

While you are correct that classes inherit from - and can be cast to - object, the cast that you are trying to perform is invalid. For the runtime to be able to perform that cast, it would have to create a new Specification and cast all of the instances of T to an object. This would be an incredibly intricate type of cast to implement, which is likely why the runtime doesn't support it.

John Glenn
  • 1,469
  • 8
  • 13