C# : Anonymous and Dynamic Types

Remember there was times when in case there is no way to identify the object type at compile time, we have to declare it as Object type which is nothing but the shorthand for System.Object class. Before diving into the topics of Anonymous type and Dynamic type in C#, lets go through the basics of Object first.

Object (or System.Object)

System.Object is the root type in the C# class hierarchy. All predefined type, used-defined types, reference types and value type all inherit from Object. But the problem with using Object is every time we need to use explicit casts to convert a variable declared as object to other specific types. Example:

object objTotal = 100;

Now lets suppose we want ot add 50 to objTotal, so we need to cast objTotal to int type before any operation on it.

obj Total = (int)objTotal + 50;

Performing this casting everytime we need to use object is not a good practice.

C# Anonymous Type (var)

Beginning in Visual C# 3.0, we get the ability to create new types ‘on the fly’ using Anonymous Type. Anonymous types are created using the an implicit typevar” keyword. Before C# 3.0 whenever we have to initialize a type we have to mention the type before we give a name for a variable or we have to use Object, but this is not the case with var. The var keyword instructs the compiler to infer the type of the variable from the expression on the right side of the initialization statement. For example:

string name = "Raman";      // A variable explicitly declared as a certain type.
var name = "Raman";         // A variable implicitly declared as the type being assigned to it.

Or for something more complex like this

studentRecord = {RollNo = 1, Name="Raman"};

Another area where var can be useful is where we need multi-column output from some LINQ query.

var students = from s in db.Students
               where s.Class == “Tenth”
               select new { s.RollNo, s.Name };


  1. It is important to understand that the “var” keyword does not mean “variant”. It just means that the compiler determines and assigns the most appropriate type instead of we assigning the type.
  2. Initialization of var in the same statement is required, it is not an optional thing. The variable cannot be initialized to null.
  3. Var can only be used as a local variables (variables declared at method scope). It cann’t be used as a return type of a function.We can’t use var to define a property on a class, nor can you use it to specify the return value or a parameter of a function.

C# Dynamic Type (dynamic)

Programming languages are roughly divided into statically typed (C#, Java etc) and dynamically typed (Python, Ruby, JavaScript etc) languages. In simple words, dynamic languages don’t perform compile-time type checks and identify the type of objects at run time only but statically typed languages performs this check at compile time. Advantage of dynamic run time checking is often the code is much faster and easier to write, but at the same time we don’t get compiler errors.

As we know C# is a static language, but with C# 4.0, new keyword dynamic is introduced.. When we use the dynamic keyword we tell the compiler to turn off compile-time checking. Example:

dynamic d=”It is a string”;
console.WriteLine(d.GetType());        //Output : System.String
d = 100;
console.WriteLine(d.GetType());       //Output : System.Int32

But then one more thing comes into picture, we instructed the compiler “Hey dude, just compile this without any check and don’t bother even if some wrong call is there”. Lets see what can happen. As mentioned above, it’s possible to assign objects of different types to a variable declared as dynamic. The code compiles and the type of object is identified at run time only. However, this code compiles as well, but throws an exception at run time:

dynamic d = "Blahblah";

d++;       //This will not give any compile time error but throws an exception at run time.

So, to overcome this problem, we manually need to make sure there are no such wrong calls.

Note :

  1. Extension methods can’t be called with dynamic.
  2. Anonymous functions( lambdas) can’t be called by dynamic.

var vs. dynamic

  1. First difference, which is clear from the above definitions is: var is all about reinforcing and improving static typing, it is anonymous but it is static and will be handled at compile time only. But dynamic keyword is about avoiding static typing all together, it will not be touched at the compile time and will be handled at runtime only.
  2. Var can only appear in the local variable declarations, we can’t use var to define a property of a class nor the return type or parameter of any function.
  3. As a developer, you use the dynamic keyword with variables expected to contain objects of uncertain type such as objects returned from a COM or DOM API; obtained from a dynamic language (IronRuby, for example); from reflection; from objects built dynamically in C# 4.0 using the new expand capabilities.
  4. The dynamic type doesn’t bypass type checks, though. It only moves them all to run time. If type incompatibilities are discovered at run time, then exceptions are thrown.

C# is Inherited as Static Language then why this Dynamic?

Well, valid question. As we can see that C# is slowly evolving into a multi-paradigm language and in a world where we must interoperate with other systems (the web, xml, json etc) and more importantly with the dynamic languages like IronPython or IronRuby etc, adding dynamic support into the language makes the things simpler.

Hope this make things a bit clear. Don’t forgot to comment your views. Happy Coding……

Tagged , , , , , , , , , , , , , , , , , ,

jQuery .bind(), .live() and .delegate methods and their differences

jQuery has three methods .bind(), .live() and .delegate(), which are used to attach events to selectors or elements. First question which comes into mind is “Why there are 3 different functions for same purpose? There should be some difference.” YES, there are some differences. In this post, we will see how these three functions are different from each other.

The difference between .bind(), .live() and .delegate() is not always apparent.


$(‘a’).bind(‘click’, function() {
alert(“Click event is fired”);

} );

This is the most basic and straight forward method for binding events. jQuery scans the complete document for all ‘a’ elements and binds the alert function to the click event of each of the matched element. The advantage of bind is we don’t need to write click event for every element (of same type). Just write the bind event and it will automatically attach to all the elements. Many CSS selectors can be used with the bind function. For example :

$(‘a.contact’).bind(‘click’, function(){
alert(“Click event of a tag with class contact is fired”);


Above code binds the click event to all the a tag which are having CSS Class “contact”.


$(‘a’).live(‘click’, function(){

alert(“Click event is fired”);


jQuery binds the above alert function to the ‘document’ element instead of each ‘a’ tag with ‘click’ and ‘a’ as parameters. Whenever any event is propagated to the document element, it check the parameters if it is a click event and the target is the ‘a’ element and executes the attached function if both the parameters are true.

.live() method works with jQuery version of 1.3 or higher.


$(‘#container’).delegate(‘a’, ’click’, function(){
alert(‘Click event is fired’);


jQuery binds this alert function with the click event and selector ‘a’ as parameters to the element with id ‘container’. Whenever any event propagates upto $(‘#container’) element, it check for the parameters whether they are click event and target is ‘a’ element. If both matches, function is executed.


On first look we can think that delegate() is more or less similar to the live() except that it binds to the specified element and live() binds to the root document. But there are differences in both of these. Which we will see later.

How bind() is different from live() and delegate() :

The basic difference between bind and both live() and delegate() is bind will not attach the event handler to those elements which are added/appended after DOM is loaded. As bind directly binds handlers to the individual elements, it cannot bind them to elements that aren’t on the page yet, but both live() and delegate() will attach the event handler to the current as well as the elements which will be added dynamically in the future.

How delegate() is different from live() :

As mentioned above, on first look both delegate() and live() looks somewhat similar. But they have their differences. Lets dig into the difference:

delegate() method is generally preferred to the live() method for few reasons. For example:

$(‘a’).live(‘click’, function(){

alert(“Live function”);



$(document).delegate(‘a’, ‘click’, function(){

alert(“Delegate function”);



delegate() is much faster than live(), because live() first scans the entire document for all ‘a’ elements, store them as jQuery objects and later on live function pass ‘a’ as a string argument which is then compared and function is executed. This happens because initially $() doesn’t know that it is chained with the live() function so it traverses the complete DOM and finds all ‘a’ elements. On the other hand delegate() method only needs to find and store the $(document) element which makes it much faste then live().

CSS selectors only

The live method has one very large shortcoming, and that is that it can only operate on a direct CSS selector string. This makes it very inflexible.


live() function can’t be used in chaining. It needs to be used directly on a selector/element. For example, if we have a div with id “divTable”, which have a table. And we want to attach a click event to ’tr’ tag of the table.

$(‘#divTable’).children(‘table’).find(‘tr’).live(‘click’, function(){

alert(‘Click event fired, tr containing’ +$(this).text());


The above code will not work. However with delegate() you can achieve this functionality.

$(‘#divTable’).children(‘table’).delegate(“tr”, “click”, function(){

alert(‘Click event fired, tr containing’ +$(this).text());



Summary :

delegate() method has more advantages and much more preferred method then bind() and live(). But as we always say, it all depends on the individual use case and choices what to use and what not.

Thats all for now… Happy Coding

Tagged , , , , , , , , , , , , ,

An Introduction to E4X

What is E4X?

E4X is a new extension to Javascript. It provides direct support for XML to Javscript. As most of us know that the official name of
Javascript is ECMAScript. Here ECMA stands for The European Computer Manufacturers Accosiation, this is the organisation standardizing
Javascript. So it is actually ECMAScript for XML in short E4X. E4X makes scripting for XML with JavaScript very
simple With the support of E4X, we can declare an XML object variable the same way as we declare object variables in Javascript.
For example:

var a = new Array()


var b = new XML()

Parsing an XML document:

Lets suppose that an XML document looks like this

    <heading>Invitation for Party</heading>
    <body>You are invited for party at my residence on the mentioned date from 6:00PM onwards!</body>

It represents an invitation from Alex to John. We can load this XML in an XML object in many ways, like if this document is stored in a string called
invitation, we could load it into an XML object ‘x’ by the following syntax:

var x = new XML(invitation);

or we can directly assign the XML to the onject like:

x = <invitation>
          <heading>Invitation for Party</heading>
          <body>You are invited for party at my residence on the mentioned date from 6:00PM onwards!</body>

Now comes how to access this object, quite simple: If we want to access from element in the example above, we can write the statement like this:

and the output will be "Alex"


The limitation of E4X is that browser support for it is very less. Infact, Firefox is currently the only browser with relative good support for E4X.
There is currently no support for E4X in Opera, Chrome, Safari or Internet Explorer etc.

Basic Syntax:

With E4X basic XML elements are valid syntax for variables, For instance
var element = <animal/>
is perfectly valid in E4X enabled browser. It is not limited to one element only it can spane multiple lines like:
var element2 = <animal><lion></lion></animal>;

We can specify all of the normal attributes on elements that we would use normally include in an XML document.

Manipulating Elements:

E4X is to provide an easier way to manipulate an XML document in Javascript, without going through the DOM interface.
For example:

var element1 = <animal/>;
var element2 = <lion/>;

this will produce the following XML document:


Javascript Variables in E4X:

The true power of E4x is that XML document can interact closely with other Javascript. With special syntax, we can assign the value of a Javascript variable to be the value of an E4X element. This is done with braces({})

var a=2;
var b=<animal>{a}</animal>

creates an XML document that reads <animal>2</animal>
These braces can be used on attributes of elements also ( their names or values). For example,

var a=4;
var b='legs';
var c=<animal {b}={a}>"hi"</animal>;

this will create XML document like this

<animal legs="4">"hi"</animal>

Accessing XML Children:

As JavaScript Objects use the .(dot) operator or [] notation to set properties.

var a = {};
a.foo = 1;
a["bar"] = 2;

in E4X, the .(dot) and [] operators provide access to the child nodes of the E4X element.

var element1 = <animal>

var element2 =<Forest animal/>;

element1["lion"].appendChild(<King of animals/>;

adds a child to the lion child node of elements. This gives an XML document of:

         <Forest animal/>
         <King of animals/>

Deleting the child node:

We can delet the child node by using the delete command:

var elem = <animal>


leaves just


The .(dot) operator can also be used to replace particular child nodes

var elem1 = <animal>
var elem2 = <red>

elem1.lion = elem2;

replaces the <lion/> element with all of the content in elem2, giving:


So, here we reached the end of this article. This is just an Introduction to E4X, for more detailed tutorial you can refer to MDN Docs E4X Tutorial.

Keep reading and Happy Coding….

Tagged , , , , , , , , , , , , , ,

Preserve Whitespaces in HTML without using ‘nbsp’

A simple but useful tip. If you want to preserve whitespaces in HTML documents without using  &nbsp; tag, you can achieve this by adding “white-space” property to the CSS style(s) of that element.

Lets see what exactly this “white-space” is?

The white-space property of CSS specifies how whitespace (spaces, tabs and hard returns) inside an element is handled. In XHTML, whitespace is collapsed. This means that multiple consecutive whitespace characters (spaces, tabs and hard returns) will be treated as a single space character. The white-space property can instruct Web browsers to change this behavior.

Properties : 

normal :   cause white space to collapse and provide line brakes where ever necessary.

pre:   prevent white spaces from collapsing and causes line to break only where new line characters are present in the code

nowrap:    causes white space to collapse but line to break only when new line character is encountered in the code.

pre-wrap:   prevent white spaces from collapsing and cause line to break where new line character is encountered or wherever else necessary for wrapping.

pre-line:   causes white spaces to wrap and line to break where new line character is encountered or wherever else necessary for wrapping.

Other Characteristics:

Value               :         normal |pre|nowrap|pre-wrap|pre-line |inherit

Default            :         normal

Applies to      :         all elements

Inherited       :         Yes

Media              :         Visual


<div style="white-space:pre-wrap;"></div>
<th style="white-space:nowrap;"></th>
<span style="white-space:pre-line;"></span>

Happy Coding……….

Tagged , , , , , , , , , , , , , ,

Difference between Int32.Parse(), Int32.TryParse() & Convert.ToInt32()

Some days back I stuck into a problem where Convert.ToInt32 was giving an exception some times. That day for the first time I explored the differences between the 3 Casting methods:

  • Convert.ToInt32()
  • Int32.Parse()
  • Int32.TryParse()

So today I am going to share with you all the difference between Int32.Parse(string), Int32.TryParse(string) and Convert.ToInt32(string) and will discuss when to use which one.

All the three casting method converts the string representation of a number to its 32-bit signed integer equivalent. Int32.parse(string) and Convert.ToInt32(string) will either return value or throw exception in case if conversion fails.  In fact Convert.ToInt32 internally calls Int32.Parse for conversion. On the other hand Int32.TryParse(string, out int) will return true if conversion is success and false if not. And the converted value will be stored in the 2nd parameter.

For clear understanding we will use the following data as an example

string s1 = null;

string s2 = “abcdefghijkl”;

string s3 = “123”;

string s4 = “123456789012345678901234567890”;

string s5 = “”;

int result;

bool sucess;

Now, lets take up these methods one by one:

Int32.Parse(string s)

In Int32.Parse(string s), if s is a null reference, it will throw ArgumentNullException. If s is other than integer value, it will throw FormatException. When s represents a number less than MinValue or greater than MaxValue, it will throw OverflowException.

result = Int32.Parse(s1);     // ArgumentNullException
result = Int32.Parse(s2);     // FormatException
result = Int32.Parse(s3);     // 123
result = Int32.Parse(s4);     // OverflowException
result = Int32.Parse(s5);     // FormatException

Convert.ToInt32(string s)

Convert.ToInt32(string s) calls in turn Int32.Parse(string s) method. When s is a null reference, it will return 0 rather than throwing ArgumentNullException. If s is other than integer value, it will throw FormatException. When s represents a number less than MinValue or greater than MaxValue, it will throw OverflowException.

result = Convert.ToInt32(s1);     // 0
result = Convert.ToInt32(s2);     // FormatException
result = Convert.ToInt32(s3);     // 123
result = Convert.ToInt32(s4);     // OverflowException
result = Convert.ToInt32(s5);     // FormatException

Int32.TryParse(string s)

Int32.TryParse(string s) is available in C# 2.0 and above. When s is a null reference, it will return 0 rather than throwing  ArgumentNullException. If s is other than an integer value, the out variable will have 0 rather than FormatException. When s represents a number less than MinValue or greater than MaxValue, the out variable will have 0 rather than OverflowException.

success = Int32.TryParse(s1, out result);     // success = false; result = 0
success = Int32.TryParse(s2, out result);     // success = false; result = 0
success = Int32.TryParse(s3, out result);     // success = true; result = 123
success = Int32.TryParse(s4, out result);     // success = false; result = 0
success = Int32.TryParse(s5, out result);     // success = false; result = 0

So now the question is which one should be used:

With respect to the Performance(Speed) order is

Int32.Parse(string) > Convert.Int32(string) > Int32.TryParse(string, out int)

Int32.Parse() method is the fastest and the most time consuming method is Int32.TryParse() because it handles all of type exceptions and never ever throw any exception.


With respect to the Robustness of the methods preference order is:

Int32.TryParse(string, out int) > Convert.ToInt32(string) > Int32.Parse(string)

Int32.Parse never checks for any kind of exception if the input is integer type it will provde the output and in all other cases it will throw an exception.

Convert.ToInt32 is better then Int32.parse because it at least check for null reference and returns 0 in case of null input.

Int32.TryParse is the most robust method. It handle all the case and make sure no exception is thrown, whatever the case maybe.

Finally, it depends on your requirements, you need to decide which one is best for you. Whether you require fastest method or the safest one.

Happy Coding…

Tagged , , , , , , , , , , , , , ,

Goggle+ the next big thing after Facebook???

The whole web is talking about Google+, the top-secret social project that Google has been working on for the past year, it is led by General Patton (Vic Gundotra) Google’s senior vice president of social.

This time, they were all working hard to do something better than Orkut and Wave. The idea was to create a product that would make a mark on the web. So Google+ is their answer to the social networking giants Facebook and Twitter. Will Google+ be able to give competition to existing social networking sites? Is this the next big thing? Only time will tell….Lets have an overview of Google+

Google+ is still in its testing phase and invitations are required to join. So, invitations are still scarce to come by. But when you are in, first thing you will notice is that you are automatically signed in a secure server(https). This may be done considering the recent controversies over Facebook taking liberties with users’ privacy. Other add on advantage with Google+ is the sleekness of it UI, its seems clean and easy to use.

Key Features of Google+ Project are:

1. Google+ Circles

Google+ Circles are very much similar to our real life circles, a circle of our college friends,  another of colleagues, a circle for our parents and relatives so on and so forth. It facilitates sharing of information among these circles while ensuring privacy. The things that you share with your college friends might not be the exact things you’d like to share with your family and colleagues. Google lets you create different circles and makes it easier to share content among the members of that circle.  Creating circles are far more easy then creating friend list in Facebook or a Twitter list, the drag and drop functionality with a nice animation is a welcome addition.

2. Google+ Hangouts

Google+ Hangouts is the next best and one of the more innovative concept. You can join a group conference with up to 10 people from your circles and have fun sharing your thoughts or just chilling out. Ohh…then how it is different from group video chat,  well the feature which makes it far better is its Camera Switching Feature means it changes who’s on the camera based on who’s talking.

3. Google+ Sparks

Google+ Sparks is a new way to engage in conversation with people.  You just need to add a topic of your interest and Google will search the Internet and deliver a stream of content directly related to the topics of your interest. Even more interesting thing is that the content will be delivered in over 40 languages. This is a great feature but it seems it will end up being the most underrated feature.

4. Google+ Huddle

Google+ Huddle is basically a group messaging service for the circles you create which lets everyone know what’s going on instantaneously. This is not that great feature but it is good to text all friends at the same time.

5. Google+ Instant Uploads

Google+ Instant Uploads is a photo sharing feature very much similar to Facebook photo sharing. But the difference is it comes with a photo editor and instant uploading from your phone. With instant uploads,  you photos and videos upload automatically to a private album on Google+ and you just need to decide who to share them with.

6. Google+ Stream

Last but not the least, Google+ Stream is the place where users will see what their friends shared. This feature  is very much similar to Facebook’s News Feed. This is THE most important feature or we can say the backbone of any social networking platform.

These are all the major features of Google+. As Google+ is still in the testing phase a debate is going on in the web community, whether it is better then Facebook or later is better. If you want to read some comparisons between Google+ and Facebook see article on Tommy.ismy.Name or on MyWindowsClub .

Or go to you tube for an Introductory Video

Lets wait and watch what more Google+ offers in coming times….

Tagged , , , , , , , , , , , , , , , , ,

Triple equal sign or Strict Equality in JavaScript

Most of the developers are familiar with single (=) and double (==) equal signs but in JavaScript there is another equal type that is Triple equal (===) sign which is called Strict Equality. What this really means? Well as double equal sign checks value to be equal, this operator tests both type and value for equivalency. In some cases, the JavaScript triple equals sign operator can simplify variable type and value checking. Here’s a simple example HTML page that illustrates the technique.

var p=1;             // Numeric Value
var q=1;             // Numeric Value
var r="1";           // String Value
var s="1";           //String Value
alert(p===r);        // Alerts 'true' as both variables are numeric,having value 1
alert(r===s);        // Alerts 'true' as both variables are string,having value 1
alert(q===r);        // Alerts 'false'as both variables are different type,having value 1</p>
<p style="text-align: justify;">

For strict equality the objects being compared must have the same type and:

  • Two strings are strictly equal when they have the same sequence of characters, same length, and same characters in corresponding positions.
  • Two numbers are strictly equal when they are numerically equal (have the same number value). NaN is not equal to anything, including NaN. Positive and negative zeros are equal to one another.
  • Two Boolean operands are strictly equal if both are true or both are false.
  • Two objects are strictly equal if they refer to the same Object.
  • Null and Undefined types are == (but not ===).

Thanks for reading…

Happy Coding…

Tagged , , , , , ,
%d bloggers like this: