-
List<Lazy<IA>> list = new List<System.Lazy<IA>>();
list.Add(new Lazy<IA>(()=>new A()));
list.Add(new Lazy<IA>(()=>new A()));
foreach(IA a in list) // Why doesn't this line throw a compile-time error?
{
a.Run();
}
public interface IA
{
void Run();
}
public class A:IA
{
public void Run()
{
Console.WriteLine("A.Run");
}
}
|
Beta Was this translation helpful? Give feedback.
Answered by
ufcpp
Sep 3, 2025
Replies: 1 comment 1 reply
-
First, as a remnant from the days before Generics, And converting a class to an interface results in an error only when the class is sealed. var a = (IA)new A(); // A derived class may implement the interface.
var a1 = (IA)new A1();
var b = (IA)new B(); // Error only when the class is sealed
interface IA;
class A;
class A1 : A, IA;
sealed class B; |
Beta Was this translation helpful? Give feedback.
1 reply
Answer selected by
jnm2
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
First, as a remnant from the days before Generics,
foreach
statement generates explicit casts.https://github.com/dotnet/csharpstandard/blob/draft-v8/standard/statements.md#13952-synchronous-foreach
And converting a class to an interface results in an error only when the class is sealed.
https://github.com/dotnet/csharpstandard/blob/draft-v8/standard/conversions.md#1035-explicit-reference-conversions