Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strange StackOverflow exception

I have the following code:

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine((Program)3);

        Console.WriteLine("Execution complete.");
        Console.Read();
    }

    public static implicit operator Program(int asd)
    { return 10; }
}

Which throws a StackOverflow exception at the last line ({ return 10; }). And I cannot figure out why, since there should be enough space on the stack for everything.

I am learning about the operator keyword and implicit/explicit converting, so I made this little example to test some tings.

like image 265
J. Doe Avatar asked Nov 22 '25 14:11

J. Doe


2 Answers

The stack overflow is caused by this method calling itself infinitely:

public static implicit operator Program(int asd)
{ return 10; }

Why does this method call itself infinitely? Well, this method defines an implicit conversion from int to Program, so you are supposed to return a an instance of Program given an int called asd. However, you return an int. Normally, this would fail, but since you defined an implicit conversion from int to Program, the compiler goes "okay, that's fine".

But at runtime, it tries to convert your 10 to a Program, by calling the implicit conversion method again. The implicit conversion method returns a 10, which the runtime tries to implicitly convert to Program again, so it calls the method again...

I don't really see what you are trying to do here, so I don't know what's a solution to this problem.

like image 130
Sweeper Avatar answered Nov 24 '25 05:11

Sweeper


If you define an implicit operator, it should return the type you specified, in this case it should be of type Program.

public static implicit operator Program(int asd)
{ return 10; }

What is happening here is that you return an integer. Normally that would simply not compile, because you should return a Program. However, since you have defined an implicit from int to Program, this is no problem; run time this conversion will be used to cast your int into a Program.

However, this conversion does not return a Program, but an int, so the conversion is called again.

When executing (Program)3, this causes (Program)10 to be called, which causes (Program)10 to be called, ... which is an infinite loop.

Ask yourself what you are actually trying to do, and why you are returning an integer when you promise to return a Program.

like image 31
oerkelens Avatar answered Nov 24 '25 05:11

oerkelens



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!