1

I have this C# code:

using System;
                    
public class Program
{
    public static void Main()
    {
        int? bar = null;
        Foo foo = bar;
        
        Console.WriteLine(foo == null);
        Console.WriteLine(foo.Val);
    }
}

public class Foo 
{
    public int Val;
    
    public Foo(int val) 
    {
        Val = val;
    }
    
    public static implicit operator Foo(int val)
    { 
        return new Foo(val);
    }
}

This is the output, I get a runtime exception, which is understandable:

True
Run-time exception (line 11): Object reference not set to an instance of an object.

Stack Trace:

[System.NullReferenceException: Object reference not set to an instance of an object.]
   at Program.Main() :line 11

But I expected this code to never compile at all. How can this code compile when there is no implicit conversion from int? to neither int nor Foo?

Same code on DotNetFiddle: https://dotnetfiddle.net/WpW2gl

starikcetin
  • 1,391
  • 1
  • 16
  • 24

0 Answers0