I found something strange for me in the output type in C #.
Example.
I have an interface
interface IInterface1
{
}
and the class that implements the interface
class Class1 : IInterface1
{
}
Then I have a function that creates a class
static Class1 GetInstanceOfClass1()
{
return new Class1();
}
And I want to use a universal function that will return an enumerable
static IEnumerable<T> GetSomething<T>() where T : IInterface1
{
yield return GetInstanceOfClass1();
}
Full code
using System.Collections.Generic;
namespace TypeInference
{
interface IInterface1
{
}
class Class1 : IInterface1
{
}
class Program
{
static Class1 GetInstanceOfClass1()
{
return new Class1();
}
static IEnumerable<T> GetSomething<T>() where T : IInterface1
{
yield return GetInstanceOfClass1();
}
static void Main(string[] args)
{
}
}
}
This code does not compile
Cannot implicitly convert type 'TypeInference.Class1' to 'T'
If I write like
yield return (T)GetInstanceOfClass1();
error message equals
Unable to convert type 'TypeInference.Class1' to 'T'
he cannot transform as before.
Ok I write how
yield return (IInterface1)GetInstanceOfClass1();
and received
Cannot implicitly convert type 'TypeInference.IInterface1' to 'T'
he cannot transform as before.
But if I write how
yield return (T)(IInterface1)GetInstanceOfClass1();
everything is fine.
Can someone explain to me what was wrong and why the code ended up compiled?
Thanks.