Cast generic type to object

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

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");

2 answers

  • answered 2022-01-23 02:48 John Glenn

    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.

  • answered 2022-01-23 03:15 Phillip Ngan

    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

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum