C # type inference, generics and interfaces

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.

+4
2

. .

,

interface IInterface2 : IInterface1 { }

GetSomething<IInterface2>()? , Class1 IInterface2.

, ,

class Class2 : IInterface1 { }

GetSomething<Class2>()?

, , , .

+8

, T IInterface1, Class1 .

:

  • T - Class1, Class1 - T = > (T)GetInstanceOfClass1()
  • IInterface , T = > (IInterface1)GetInstanceOfClass1(),

, :

, Class1 IInterface, Class1 . , T IInterface, , . , , , .

.

object o;
o = 5;
string s = (string)o;

, .

+3

Source: https://habr.com/ru/post/1610370/


All Articles