Wednesday, August 16, 2006
« Why xml-script? | Main | Google Groups Link Missing! »
In JavaScript, I commonly use the "OR" operator to determine the first non-null value. This trick allows me to quickly write cross-browser event handlers:
 
    1 function myEventHandler(evt) {
    2    evt = evt || window.event;
    3    // handle event here
    4 }



This long-hand version is functionally equivalent:
 
    1 function myEventHandler(evt) {
    2    if(typeof evt != "undefined") {
    3       evt = evt;
    4    }
    5    else {
    6       evt = window.event;
    7    }
    8    // handle event here
    9 }



Well, I just discovered that C# has an equivalent construct to JavaScript's "OR" assignment - the "??" operator:

    1 static void Main()
    2 {
    3     string str1 = null;
    4     string str2 = null;
    5     string defaultValue = "My default text";
    6     string display = str1 ?? str2 ?? defaultValue;
    7 
    8     Console.WriteLine(display);
    9     // output: "My default text"
   10 } 



Ah, sweet syntactic sugar... is there an equally elegant way to do this in VB.NET?
Thursday, August 17, 2006 12:42:07 AM (Central Daylight Time, UTC-05:00)  #    Disclaimer  |  Comments [0]  | 
Name
E-mail
(will show your gravatar icon)
Home page

Comment (Some html is allowed: a@href@title, b, blockquote@cite, em, i, strike, strong, sub, super, u)  

Enter the code shown (prevents robots):