nikhilk/scriptsharp — Issue #116: Comparison against zero emits wrong JavaScript
Author: ecm-mclay
Created: 2011-10-26 00:09:29+00:00
State: open

In Script# 0.7.3 and 0.7.4, and possibly earlier versions, comparisons against zero emit the wrong JavaScript.

This C# code:

```c#
int? x = null;
if (x == 0) { }
```

Emits this JavaScript code:

```javascript
var x = null;
if (!x) { }
```

Instead of the correct JavaScript code:

```javascript
var x = null;
if (x === 0) { }
```

If the value being tested was a non-zero integer value like this:

```c#
int? x = null;
if (x == 1) { }
```

Then the correct code is emitted:

```javascript
var x = null;
if (x === 1) { }
```

This is a problem not only for nullable types, but also for code that accepts external input where the variable type may not be correct (such as an empty string being passed in where an integer is expected).

A similar problem also exists with != comparisons:

```c#
int? x = null;
if (x != 0) { }
```

Results in this code:

```javascript
var x = null;
if (!!x) { }
```

Which is at least consistent, since null is considered equal to zero in both cases.

The problem is worse in 0.7.4 now that constants and enums are inline. In 0.7.3, constants and enums with a value of 0 would cause the correct comparison to be emitted. Now that they are inline the incorrect comparison is emitted.

Comparisons in C# using == and != should emit === and !== respectively in JavaScript to avoid treating values like null as equal to zero.