C# Trivia #6

Published 12-06-2007 1:43 PM | jokiz

As I've mention in this post, I'll be continuing the trivia series here in my blog.  I've encountered a good one from internal chat yesterday, here it is:

will this compile?

[Test]

public void IntTests()

{

    int i = 1;

    if(i != null)

    {

        Debug.Write("jokiz");

    }

}

Filed under: ,

Comments

# bonskijr said on December 6, 2007 1:20 AM:

compile nman.. whats the trivia? always evaluate to true? heheh

# Pieter Joost van de Sande said on December 6, 2007 1:37 AM:

Yes, and you'll get a compiler warning I geus.

# Pieter Joost van de Sande said on December 6, 2007 1:37 AM:

Yes, and you'll get a compiler warning. It is strange, since it isn't a nullable type.

# jokiz said on December 6, 2007 8:06 AM:

trivia is about int, value types and nulls, gets?

# cruizer said on December 6, 2007 10:39 AM:

of course it won't compile! there's no "using NUnit.Framework" or "using MbUnit.Framework" at the top!

joke lang po, master... he he :D

# Brendan said on December 6, 2007 10:48 AM:

Yes, it will build and Visual Studio will call you a moron (warning) because i can never be null. It is a value type not a reference type.

Add a ? after the word int and it will work.

# jokiz said on December 6, 2007 7:12 PM:

sorry about that bossing, i'll post a complete class instead next time if you like, ;p.

Note that this method compiles fine with a warning in VS 2005, but not in VS 2003

# jakelite said on December 10, 2007 7:00 AM:

i guess integers are autoboxed on conditionals as expected. whats interesting here is that the compiler optimizes away the condition on the if statement and replaces it with 1 != 0 with no jump statements in IL. and this happens even when the condition involves a function returning an integer. interesting discovery. thanks!

# jokiz said on December 10, 2007 8:25 AM:

autoboxed in conditionals?  i have no idea actually about this. there is a blog post somewhere related to this and he basically says that int alias in c# is mapped to nullable int which i found to be bogus.

# jakelite said on December 10, 2007 8:22 PM:

value types when assigned to a variable of type object are implicitly boxed. so the comparison between i and null now works because of this. there must be a bug in 1.x causing it to not compile. but since they can never be equal the compiler optimized it away. which is really amazing. compiler optimizations is always an interesting topic.

# Genric name for ultram. said on June 5, 2008 6:09 AM:

Ultram.

# Propecia information from drugs com. said on July 27, 2008 11:53 PM:

Propecia contraindication in women.

# Zolpidem online. said on August 5, 2008 10:33 PM:

Zolpidem.

# Work from home jobs. said on November 2, 2008 2:30 PM:

Envelope stuffing work from home. Work at home. Work home time tracking software.