Cast generic type to object [duplicate]
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");
}
}
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
toobject