Monday, September 5, 2011

Using comparison operators in a unsafe way

// Using operators in a unsafe way

// declare a variable to null
string s = null;
// for the 'or'  operator comparison
// if left side get true the right side will never be invoke
// if left side get false, the right side will come.
// in this example below will be fine because the right side won't be invoke when
left side is true.
if(s == null || s.Length == 0)

// for 'and' operator comparison
//
if left side get true the right side will invoke
// if left side get false the right side will never invoke
// this example below will be throw a exception while right side is execute.

if(s == null && s.Length == 0)


// declare functions
func1(param){return param;}
func2(param){return param;}

//                                                which function being call
if(func1(true) && func2(true))     func1   func2
if(func1(false) && func2(true))    func1
if(func1(true) || func2(true))         func1
if(func1(false) || func2(true))        func1   func2


// the concept above can also apply to C/C++, java and javascript ....