Nothing != null - or does it?

2019-06-15 08:09发布

问题:

Recently in a previous project I came across a peculiar difference between VB.NET and C#.

Consider the following C# expression which:

null <= 2

This expression evaluates to False which is what I would expect. Then the corresponding VB.NET expression:

Nothing <= 2

I was surprised to learn that this expression actually evaluates to True

It seems like a fairly fundamental design decision between the two languages and it certainly caught me out.

Is anyone able to tell me why? Are null and Nothing one and the same? If so, why do they behave differently?

回答1:

Nothing in VB evaluates to the default value for a given type. (See this link for details.)

For an integer comparison (which the compiler will assume from the right hand operand), Nothing will thus be 0. 0 <= 2 is true for more obvious reasons :-)



标签: c# .net vb.net clr