Is there anything you can do to make this function return "False" ?
bool CrazyFunction(int radius)
{
const double pi = 3.14;
var perimeter = 2 * pi * radius;
return perimeter == 3.14 || perimeter != 3.14;
}
Scroll for the Answer
The Short Answer
Add the following to the class where our CrazyFunction exists.
struct var
{
public static implicit operator var(double value)
{
return new var();
}
public static bool operator ==(var first, var second)
{
return false;
}
public static bool operator !=(var first, var second)
{
return false;
}
}
The Long Answer
If you think the trick is about operator overloading, then you were close to the answer.
But how would you overload the `==` (or `!=`) operator for System.Double ?
Do you even need this ?
The trick of this puzzle is about `contextual keywords`. In C#, there are two distinct types of keywords, the `keywords` (like if, for, class.. etc) and `contextual keywords` (like var, async, dynamic.. etc).
For contextual keywords, the compiler decides whether to deal with them as keywords or not, based on the context where they are used.
For example, in the following statement, the compiler will deal with the first `var` as a keyword, and the second one as a variable name.
// declaring a variable named 'var' and initializing it to 5
var var = 5;
Back to our puzzle; if we have defined a struct named `var` like this:
struct var
{
...
}
Then the compiler will understand the following statement as declaring a variable named 'perimeter' of the type 'var'.
var perimeter = 2 * pi * radius;
And this way we can easily overload the `==` and `!=` operators to make them return false.
Bingo!