Why is this code not compiling, although interfaces are reference types?

I am embarrassed. Q Why are interfaces in .Net referenced types? It says that interfaces in .Net are reference types. The first piece of code does not compile. He says something like "T must be a reference type ..."

public ISomeInterface DoMagic<T>(Expression<Func<object>> action, Tuple<string, DateTime, decimal> tuple) where T : ISomeInterface { Magician m = new Magician(); return m.Magic<T>(()=> action, tuple.Item3); } 

The second compiler.

  public ISomeInterface DoMagic<T>(Expression<Func<object>> action, Tuple<string, DateTime, decimal> tuple) where T : class, ISomeInterface { Magician m = new Magician(); return m.Magic<T>(()=> action, tuple.Item3); } 

If interfaces are reference types, why doesn't the first code snippet compile?

+4
source share
2 answers

Because it concerns the real type of object encapsulated inside the interface. ISomeInterface simply ISomeInterface , you are not defining a must: T condition to be a reference type.

Because I can have:

 public interface IStructInterface { } public struct A : IStructInterface { } 

and this is the type of value.

By defining an additional class of constraints, you declare that it is a reference type.

+6
source

What is the error message you get when Magic has a class constraint:

 public ISomeInterface Magic<T>(Func<object> a, decimal d) where T:class 

This may be better worded, but when he says: "T must be a reference type ...", it actually means that "T is class-limited." This code generates the same error as the OP:

  class ABC { public ISomeInterface DoMagic<T>(Expression<Func<object>> action, Tuple<string, DateTime, decimal> tuple) where T : ISomeInterface { Magician m = new Magician(); return m.Magic<T>(() => action, tuple.Item3); } } interface ISomeInterface { } class Magician { public ISomeInterface Magic<T>(Func<object> a, decimal d) where T:class { throw new NotImplementedException(); } } 

The type ' T ' must be a reference type in order to use it as a parameter ' T ' in the generic type or method ' ConsoleApplication4.Magician.Magic<T>(System.Func<object>, decimal) '

0
source

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


All Articles