Thursday, September 29, 2016

Before moving on with the post, just consider the following very simple JavaScript code.

x = 5;

var x;

console.log(x);

If you think the above code will give an error, then I am sorry, you might not know what JavaScript Hoisting is. Above will print "5" to the console without any errors. The reason is Hoisting in JavaScript.

Basically JavaScript Hoisting is moving declarations to the top while the JavaScript Interpretation. Even though you have written you code like above, following is what actually gets executed.

var x;

x = 5;

console.log(x);

Notice that declaration of x is being moved to the top.

Now let's take a look at what's Hoisting’s effect on functions. Consider the following code. Here I have two functions, one is a function declaration and the other is a function expression.

foo();

bar();

function foo() {

console.log("foo");

};

var bar = function() {

console.log("bar");

};

Here if you run this, "foo" will be printed on the console, and then when the call to bar() is getting executed, it will throw TypeError: bar is not a function. What’s happening here is again Hoisting. What is getting executed is the following code.

var bar;

function foo() {

console.log("foo");

};

foo();

bar();

bar = function() {

console.log("bar");

};

Here is also the declarations has moved to the top.

Now I hope you figured why it is so important to understand this little but very critical concept.

Let’s go by a very simple example. Consider the following Employee POCO class and a List<Employee>. For the sake of argument, let’s say Id is a primary key and cannot be duplicated.

publicclass Employee

{

publicint Id { get; set; }

publicstring FirstName { get; set; }

publicstring LastName { get; set; }

}

List<Employee> employees = new List<Employee>()

{

new Employee()

{

Id = 1,

FirstName = "Jaliya",

LastName = "Udagedara"

},

new Employee()

{

Id = 2,

FirstName = "John",

LastName = "Smith"

}

};

Now imagine, I want to get the Employee who is having a particular Id. In this case, I can use either First() or Single().

employee = employees.First(e => e.Id == 1);

employee = employees.Single(e => e.Id == 1);

Technically there is nothing wrong using either of them, but practically or in the best practice perspective, it’s ideal to use Single() instead of First(). Because when we say First(), it means that out of set of matching rows, I am interested in the First() item. But in our case, we know that there can only be one Employee having a particular Id. FirstOrDefault() and SingleOrDefault() are just null handling counter parts of First() and Single(). Basically what it will do is, it will return null if no matching record is found, where as First() and Single() will throw System.InvalidOperationException: Sequence contains no matching element when no matching record is found.

Now consider the following example where I want to get the Employee whose FirstName starts with a particular letter/word (well, it's not a ideal scenario, but again for the sake of argument).

employee = employees.First(e => e.FirstName.StartsWith("J"));

employee = employees.Single(e => e.FirstName.StartsWith("J"));

Here using First()/FirstOrDefault() is the ideal approach as there can be many employees whose FirstName starts with a particular letter/word. But use of Single()/SingleOrDefault() in such scenario will throw System.InvalidOperationException: Sequence contains more than one matching element as there can be many rows which matches that criteria.

So what to get from this? Always use Single()/SingleOrDefault() if you know that there can be only one record which matches the given criteria as that will improve the code readability. Use First()/FirstOrDefault() if you know that there can be many records which matches the criteria and you are only interested in the first record.

Here when you run this, still no query will get executed against the database and that’s because IEnumerable<T> and IQueryable<T> has deferred execution. You need to either iterate through or do a ToList().

Let’s consider the following scenario. Let’s add another Where on eMales which is of type IEnumerable<T> and take it into a List<T> and see how the underlined query looks like.

You can see that on there WHERE condition has only Gender related condition but nothing on MaritalStatus. So here what’s happening is, it will first select the males into the memory and then select singles from there. Not so efficient.

Now let’s add the Where on qMales which is of type IQueryable<T> and take it into a List<T> and see how the query looks like.

If we did this on eMales which is of type IEnumerable<T>, it will be selecting the all males with their all properties (like last IEnumerable<T> example) from the database, and do the rest in memory. But here IQueryable<T> is smart enough to combine all the Wheres and only Select what is projected.

Isn’t that great. I am sure with right use of these, you can make your code more efficient.

Tuesday, September 6, 2016

In this post let’s see the use of Conditional attribute and how it differs from #if directive.

It’s always best to go by an example. Consider the following.

Example 1

using System;

using System.Diagnostics;

namespace ConditionalAttributeDemo

{

class Program

{

staticvoid Main(string[] args)

{

SayHello1();

}

staticvoid SayHello1()

{

Console.WriteLine("Hello World 1");

}

}

}

It’s more than simple. If we run this “Hello World 1” will be printed on console. Now imagine that I want the method to be run only when a given condition satisfies. I know you can think of variety of ways to achieve that. But here the condition is based on a compilation symbol (DEBUG etc.).

Now let’s modify the code adding a compilation symbol named SOMETHING.

Example 2

#define SOMETHING

using System;

using System.Diagnostics;

namespace ConditionalAttributeDemo

{

class Program

{

staticvoid Main(string[] args)

{

SayHello1();

}

[Conditional("SOMETHING")]

staticvoid SayHello1()

{

Console.WriteLine("Hello World 1");

}

}

}

Now if we run this application, again "Hello World 1" will be printed on the console. And if we commented out the first line "#define SOMETHING", SayHello1() method will not get called thus the application will not print anything. It’s basically because the condition fails.

Now as you might aware, I can do the same using #if directive. Let’s modify the code to use #if.

Example 3

#define SOMETHING

using System;

namespace ConditionalAttributeDemo

{

class Program

{

staticvoid Main(string[] args)

{

#if SOMETHING

SayHello1();

#endif

}

staticvoid SayHello1()

{

Console.WriteLine("Hello World 1");

}

}

}

This will print “Hello World 1” and if we commented out the SOMETHING symbol, SayHello1() method will not get called. It’s basically Just as in Example 2. So now you must be wondering what’s the difference between Conditional attribute and #if directive. Let’s move on.

The first difference is, when you use #if, the code which is wrapped between #if and #endif, will only get compiled if the condition next to #if is true. Basically you can write almost anything within the #if and #endif and as long the condition is false, it will not throw any compilation errors (even if there are any).

The second and most important difference is, how IL is emitted in both these scenarios. When you use #if, the IL for code within the #if and #endif, will only get emitted if the given condition is true. Where as when you use Conditional attribute, IL will be emitted based on the method calls. Confused?, let’s go by the example. Let me modify the code to use both Conditional attribute and #if, and then let’s compare the IL which gets generated.

Example 4

#define SOMETHING

using System;

using System.Diagnostics;

namespace ConditionalAttributeDemo

{

class Program

{

staticvoid Main(string[] args)

{

#if SOMETHING

SayHello1();

#endif

SayHello2();

}

staticvoid SayHello1()

{

Console.WriteLine("Hello World 1");

}

[Conditional("SOMETHING")]

staticvoid SayHello2()

{

Console.WriteLine("Hello World 2");

}

}

}

Now after compiling the code, let’s see what the generated IL is (here I am using ildasm.exe).

ildasm.exe

Here let’s see what we have for Main() method.

IL for Main()

You can see that IL is generated for two method calls SayHello1() and SayHello2(). Now let’s commented out the compilation symbol SOMETHING, compile the code and examine the emitted IL back again.

IL for Main()

Now there is nothing on SayHello1() and SayHello2() method calls in Main() method. Still no difference. Let’s come to this later in the post again.

Now let’s modify the code further as below.

Example 5

//#define SOMETHING

using System;

using System.Diagnostics;

namespace ConditionalAttributeDemo

{

class Program

{

staticvoid Main(string[] args)

{

#if SOMETHING

SayHello1();

#endif

SayHello2();

}

staticvoid SayHello1()

{

Console.WriteLine("Hello World 1");

SayHello3();

}

staticvoid SayHello2()

{

Console.WriteLine("Hello World 2");

SayHello3();

}

[Conditional("SOMETHING")]

staticvoid SayHello3()

{

Console.WriteLine("Hello World 3");

}

}

}

Take a note that, I have the first line commented out (otherwise, there won’t be any difference). Now let’s compile and examine the IL on Main() method back again.

IL for Main()

And now, you should be able to see a clear difference. There is nothing on SayHello1() method call, but you can see the IL code for SayHello2() method call.

The reason is, now the call to our conditional method (SayHello3()) is done through intermediate method (SayHello2()). And you can see, even if I use the same approach in #if scenario, but still no IL was generated for that.

And now the reason for IL code to be same on Example 4 is, in that case we were directly calling a conditional method (SayHello2()) from the Main() method. And since the condition is false, compiler knows it can’t call the SayHello2(). Because of that no IL code is generated for conditional (SayHello2()) method call.

Hope this post gives you a clear understanding on Compilation attribute and it’s difference between #if directive.