Ahmed El-Halwagy’s Blog

C# 3.0 New Features – What made LINQ possible! (part 1)

Posted on: November 19, 2008

Here’s a simple problem. Suppose that you have an array of string and you want to filter this array to extract all the items in it that end with the word “Halwagy” the code would more or less look like the following.

string[] names = { “Ahmed Halwagy”, “Mohamed Halwagy”,

“Mohamed Fayad”, “Walid Hamad”,

“Ibrahim Halwagy”,

“Mohamed Shokry”,

“Amr Badawy” };

 

//TODO: Print all the halwagys in the previous list.

//1- Traditional approach

List<string> result = new List<string>();

foreach (string s in names) {

if(s.EndsWith(“Halwagy”))

result.Add(s);

}

foreach (string s in result) Console.WriteLine(s);

I assume that the code listing above is self explanatory, but anyways what’s happening here is you have this string array “names” so you traverse each element in this array and check if it ends with “Halwagy”; if so you add it to your result List<string> to eventually manipulate it as you want.

Now take a look at the next syntax (assuming we have the string array “names”):

//2- New approach (LINQ)

var halwagys = from s in names

where s.EndsWith(“Halwagy”)

select s;

foreach (string s in halwagys) Console.WriteLine(s);

Can you feel it? Can you feel the shift?

Yes it does, it looks like SQL but it’s not SQL.

Now I assume that syntax needs a lot of explanation because it really contains a lot of strange words like var, from, where, select, etc.

So before we digg into an explanation of this statement, let me breifly mention some of the new features in c# 3.0 then we will comeback to this.

First thing we will check now is called Implicitly Typed Local Variables.

C# is a strongly typed, static language which means that you can never declare a variable without identifying its data type; otherwise the compiler will generate an error. For example the statement “x = 20;” will generate a compile time error because you haven’t specified the data type of x explicitly to the compiler so to make that work you had to state that x is an integer like so “int x = 20;”. Now if you tried to change the value of x to another value that is from a different type (e.g. float) like “x = 12.5f” the compiler will generate an error now stating that it failed to implicitly convert from float to int and an explicit conversion is required.

Now take a look at the following:
var x = 20;
what the hek is that? Well appearantly this is not the same as “int x = 20;”. Actually it is the same, when you declare x as int the compiler knows that x is of type System.Int32 and we you declare x as var the compiler will check the value assigned to x, and will automatically infer the type of x based on the type of that value. so in this case the compiler will be able to infer x is of type System.Int32, and this happens automatically.


PS: The type of x will be known in the compile time not in the run time.
<!–[if !supportLineBreakNewLine]–>
<!–[endif]–>

You should know that you can use implicit typing (the var keyword) for any type in the base class library, including arrays, generics, and your custom classes. Take alook at the following examples:
var x = 12.5f; //x is float.
var list = new string[] { “C#”, “LINQ”, “.NET 3.0” }; // list is an array of string
var y = list.Length; //y is int.
//using implicit typing in foreach loop.
foreach(var tech in list) { //tech is string
Console.WriteLine(tech);
}
Restrictions on Implicit Typing:
1- Implicitly typed variables must be be locals (in a method or a property scope).
2- Local variables declared using var keyword must be assigned an initial value at the time of declaration, and this value can’t be null. (because, as you may recall, the compiler will infer the type through that value. So the compiler won’t be able to know the sort of type in memory, that the variable will point to by only null).
3- Like any normal strongly typed variable, implicitly typed variables can’t hold a value of a different data type than its original one.


Here’s a code example with the restrictions of the var keyword:
class UnCompilable {

//Error: the contextual keyword var may only appear within local variable declaration

var x = 20;

 

void DoSomething() {

//Error: Implicitly-typed local variables must be initialized.

var y;

//Error: can’t assign <null> to an implicitly-typed local variable.

var yy = null;

var onlyString = “Ahmed”;

onlyString = “This is ok”;

//Error: can’t implicitly convert type int to string. remeber, it’s a string

onlyString = 2;

}

}

 

The rest of the features will be posted soon.


 

 

Advertisements

2 Responses to "C# 3.0 New Features – What made LINQ possible! (part 1)"

Reveals a lot of things, Thanks Halwagy for the nice post.

Hi Mr : Ahmed I’m really happy to see your blogs .

My regards

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Calendar

November 2008
S M T W T F S
    Dec »
 1
2345678
9101112131415
16171819202122
23242526272829
30  

Categories

Delicious

Recent Twitter Updates

%d bloggers like this: