Thursday, July 17, 2014

Extending the Number object in JavaScript & the int type in C#

We will add a method to the Number prototype property in JavaScript. In C#, we will code the equivalent functionality with an extension method on int. Yep, we're going native! I'm hoping this will help somebody trying to move from C# to JavaScript or vice versa.

The JavaScript code can be found on GitHub here. The C# code can be found on GitHub here. You can fork the projects or just copy the code you need. Everything you need to run and test the code are in the projects. There is a QUnit page for the JavaScript project and a Unit Testing project for the C# project.

Let's start with JavaScript. All you need to do is add a method to the Number prototype property. I'm wanting to check if the Number is divisible by the dividend argument's value. I add isDivisibleBy to the prototype property and set it to an anonymous function with a dividend parameter. The function returns a Boolean:

 Number.prototype.isDivisibleBy = function(dividend){  
   return this % dividend == 0;  
 }  

You use it like so:

 var i = 6;  
 if (i.isDivisibleBy(3)) {  
       //it is and so do stuff  
 }  

There's a little bit more to do in C# but not much. We will add an extension method for int. Here, the first parameter is the type preceded by this and in our case it is our denominator. We also add our dividend parameter.

 public static bool IsDivisibleBy(this int denominator, int dividend)  
 {  
    return denominator % dividend == 0;  
 }  

To use it, it is EXACTLY the same syntax as JavaScript. The only difference is the method naming style. The method name starts with lowercase in JavaScript and starts with uppercase in C#. You could also use int instead of var in C#. But, it's all the same in the end.

 var i = 6;  
 if (i.IsDivisibleBy(3))  
 {  
     //it is so do stuff  
 }  

No comments:

Post a Comment