Wednesday, March 8, 2017

C# Puzzle: Crazy Function Always Returns True



Is there anything you can do to make this function return "False" ?
Obviously, without changing it.


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!

Friday, September 23, 2016

JavaScript Puzzle: Questions With Interesting Answers

Questions

Question (1): What is the value of typeof(NaN) ?

Question (2): If 08 === 8 and 09 === 9 are true, then, will 010 === 10 be true?

Question (3): Again.. If Infinity === Infinity and undefined === undefined, will both evaluate to true, Will NaN === NaN be also true?

Question (4): In many programming languages division by zero will throw an exception, but in JavaScript, what will be the value of x when var x = 123 / 0; ?

Question (5): You just learned that division by zero will evaluate to Infinity.. so you can tell what's the value of x when var x = 0 / 0; .. easy, right ?

Question (6): If arr is an array, then arr.length will be increased or decreased after calling arr.push and arr.pop respectively. What is an easy way to make arr.length equals 50 ?

Question (7): If null <= 0 is true, does that mean null < 0 or just means null == 0 ? (Hint: null >= 0 is also true)

Question (8): If this code will show an alert message if ([]) { alert('hi'); }, what's the output of this if ([] == true) { alert('hi'); } ?

Question (9): Which of the following will return true ?

  • isNaN(true);
  • isNaN(null);
  • isNaN("");          // empty string
  • isNaN("   ");         // string with one or more spaces


Scroll for answers





























































































































Answers

Answer (1) We all know that NaN is Not-A-Number, but some folks don't know that typeof(NaN) is "number".

Answer (2) No, 010 is not equal to 10, because JavaScript will deal with any number that starts with "0" and contains no digits greater that 7, as an octal (base 8) number.

Answer (3) No, NaN is not equal to NaN. (However, we don't blame JavaScript for that, it's the IEEE-754 spec for floating-point numbers).

Answer (4) No, it will not be undefined, x will be Infinity.

Answer (5) Exactly, x will be.. NaN.

Answer (6) arr.length = 50; in Javascript you can set the length of the array to expand or trim it.

Answer (7) Neither, both of them is false, although null <= 0 is true. It's all about how the '<=' operator coerces its operands.

Answer (8) No alert, The '==' operator coerces the value of an empty array to 'false'.

Answer (9) All of them will return 'false'

C# Puzzle: Questions on Extension Methods

Question (1):
What is the output of the following program ?



public class Program
{
    public static void Main()
    {
        var obj = new MyClass();
        obj.SayHello();
    }
}

public class MyClass
{
    public void SayHello()
    {
        System.Console.WriteLine("Hello, Original");
    }
}

public static class Ex
{
    public static void SayHello(this MyClass obj)
    {
        System.Console.WriteLine("Hello, Extension");
    }
}

Question (2):
What is the output of the following program ?



public class Program
{
    public static void Main()
    {
        var obj = new MyClass();
        obj.SayHello();
    }
}

public class MyClass
{
    
}

public static class Ex1
{
    public static void SayHello(this MyClass obj)
    {
        System.Console.WriteLine("Hello, Extension1");
    }
}

public static class Ex2
{
    public static void SayHello(this MyClass obj)
    {
        System.Console.WriteLine("Hello, Extension2");
    }
}

Answers
  1. The program will print "Hello, Original", because when the instance method and the extension method both have the same signature, the instance method will always have higher priority.
  2. The program will cause a compile-time error, because the call of "SayHello" function is ambiguous between two extension methods in classes "Ex1" and "Ex2".

Friday, December 25, 2015

C# Puzzle: Non-void functions without return statements that will compile successfully

When you try to compile the following function, the C# compiler will complain that "not all code paths return a value".

int MyMethod()
{
}

Of course if you return a value, the compiler will stop complaining. But is it always required to return a value in a non-void function ? Can you compile a non-void function without a return statement ?



Scroll for the answer






















































































































































Answer


Yes, you can..
In C#, the return statement is not required in non-void functions, and can be omitted in two cases (AFAIK).

1. Functions with unreachable endpoint

A function that throws exceptions in all code paths, is an example of a function with an unreachable endpoint, that will compile successfully without a return statement.


int MyExceptionalMethod()
{
    // Do something..
    throw new Exception();
}

Functions with infinite loops are also another type of unreachable endpoint functions, like this one:

int MyInfiniteMethod1()
{
    while (true
    {
       // Do something forever..
    }
}

Or this one:

int MyInfiniteMethod2()
{
    MyLabel:
    // Do something again and again..

    goto MyLabel;
}


2. Async functions that return a Task

async Task MyMethod4()
{
    // await for something..
}


References: