Ahmed El-Halwagy’s Blog

Moved!

Posted by: Ahmed on: November 3, 2009

Hello there,
Sorry, but this blog has been moved to This Site.
This site will remain as is with no updates –only the old articles will stay here. To get the new articles that I write, please visit my other blog
So .. See you there pals! :)

C# 4.0 Now Consumes Indexed Properties

Posted by: Ahmed on: November 2, 2009

If you dealt with COM Interop before, then you probably know what Indexed Properties mean. If you don’t, hang on with me and you will know in the coming few lines. Consuming Indexed Properties is a new feature to C# 4.0 Beta2. This is used to improve syntax like the following:

var excel = new Microsoft.Office.Interop.Excel.ApplicationClass();

excel.get_Range(“A1”);

This syntax can now be improved to get rid of get_Range(“A1”) and use an indexer accessor instead, here’s how C# 4.0 Beta 2 can do for you to improve this:

var range = excel.Range[“A1”];

So now, every time you use COM Interop and have to call get_x() and set_x(), you can now replace this with the new indexer syntax. I have to tell you –Well, you might have guessed it- that this is just a syntatic sugar, the compiler will do emit calls to get_x() and set_x() ultimately.

I think this little syntax improvement is pretty neat, however, people shouldn’t ask the very expected question “Well, now we can consume indexed properties in c#, why can’t we create it? we wanna create indexed properties! Indexed properties is a legal right! blah blah .. “. If C# allowed us to create indexed properties then I think, this will add an ambiguity that isn’t worth anything here. I mean take a look at the following code and tell me what would it mean to you, if C# enables you to create indexed properties?

obj.SomeProperty[1]

Does it mean that SomeProperty is a type that implements an indexer, or SomeProperty is a property that requires an indexer? See the ambiguity?

 

What’s your thoughts on this, dear reader?

When the increment is happening?

Posted by: Ahmed on: August 20, 2009

In my last post when I linked
to a very interesting article on Eric Lippert’s blog.
Now I want to follow up on the subject of the post increment (++) operator.

Personally I used to think the the post increment operator will increment the value of its operand at the very end of the current
statement (i.e. just before the terminating “;”). So according to my understanding, this expression (x+(y++)+y) would evaluate to 0–
of course of both x and y were initialized to 0.

If you tried this example in the C# compiler you would find that the result of
the expression is 1! (yes not 0 :S). Obviously I was wrong! Here’s how I thought the sequence of evaluating this expression (z = x+(y++)+y;)
would go: First, x is added to y and the result is stored somewhere (a for example)
Second, the result of (#First) will be added to y again (note: y here is still 0, the increment didn’t happen yet)
and the result of this evaluation is stored somewhere (b for example)
Third, the assignment will happen; assigning the result of (#second “b”) to whatever on the left side of the “=” operator.
Fourth: Now (and only now) increment y. y = 1 now.

If this is right, I would get 0 as a result of Console.WriteLine(z); but it is NOT. This flow of evaluation is not correct.
My understanding of the
post increment operator is not right! (I’m doomed, eh!?).

So I checked up the c# documentation, still couldn’t find any specific statement
about when exactly the increment happens. After an hour on the internet, I turned to my favorite site, my
third place
now, Stackoverflow.com.

I logged in and posted a question.
Go ahead click the link and check the accepted answer, if you’re lazy, here’s my summary of the answer.

First you have to know that the ++ operator has an operation to perform with a specified precedence and a SIDE EFFECT. In short, the ++
operator has the higher precednce than (* + – /). See the specs
This means that the operator will execute instantly! Yes Instantly! So the increment will be the first thing to happen (even if it’s
post increment or pre-increment). The difference between pre and post comes from the side effect. When post incrementing the old value is
stored, then the increment happens (i.e. the value of the variable increments),
and the value that’s used to continue evaluating the expression is the (yeah, you guessed it) old value.

So to get back to the example (z = z +(y++) +y;), the order of evaluating this expression would be as follows:

  1. Store the value of y somwhere -say a. a now = 0.
  2. Increment y (remember the increment has the highest precednece).
  3. Add x to the value of a(which is the old value of y; that’s the side effect part of the operator) and save the result of
    the addition somewhere (say b). now b = 0;
  4. Add the value of b to the value of y (what’s the value of y now? yes you’re right, it’s 1), and store the result somewhere
    say c. say now = 1.
  5. Assign the value of c to z. z now = 1.

As you can see, the increment happens instantly. And its side effect forces the use of the old value of the incremented variable
for evaluating the very next part of the expression. After that when trying to dereference the incremented value and get its value,
you will actually get the incremented value.


Makes perfect sense to me now. What about you dear reader?

Operator’s Precednce vs The Order of Evaluation

Posted by: Ahmed on: August 11, 2009

A little ago Eric Lippert took a stand to the programming myths that people have about c#. Starting by his awesome The stack is an implementation detail
then Not everything derives from object and today’s Precedence vs Order, Redux. I have to say it was an awesome job, very nice articles -just like everything Eric writes. I strongly recommend that you scan through these articles, a lot of mysteries to be unveiled there. I’m not going to repeat what Eric said because I’m too proud to do! Well, not really! It’s just I’m not as good as Eric to think of providing new versions of his articles (what new would these new versions have anyway?) I just want to stop by the last article Precedence vs Order, Redux. I had a nice 12 parts conversation on facebook with one of my friends. At first I posted a Twitter post with a question and a link to Eric’s article. I got a comment from one of my friends –who stands to be one of the very best students at Century 21, IBM. The man’s comment was “value = 1″. Nice and easy! Well, that wasn’t what I expected from this friend -I know the answer, I run the sample code, and seen the value of value :) , and I read Eric’s article. What I expected him to say is 0. Because as far as I know, this program should work this way:

1- Get the value of arr[0] .. the inner expression arr[0] .. 0 returned

2- Get the value of arr[0] again .. the outer arr[arr[0]] .. still 0 returned

3- Now assign the value of 0 to the variable value.

4- Now and not before now, Increment arr[0].

Apparently what I know is wrong. The increment didn’t happen the moment I expected it to happen –after assigning the value. Actually it happened before assigning the value. Frankly I don’t understand why!? I tried to search the C# spec and couldn’t find anything to state strictly when the increment should happen in case of post increment and pre-increment.
Another interesting and confusing case is a snippet I saw in a comment by Peter Ibboston on the same article by Eric:

The one that confused me is this C# code which gives different results in C & C#

int[] data={11,22,33};int i=1;data[i++]=data[i]+5;

I couldn’t find a bit in the C# spec that said anything about when increment should happen. I had presumed that the rvalue would be evaluated first followed by the lvalue.

Any ideas where I missed it.

To finalize I would say, there’s no documentation to specifically tell when the increment will happen –AFAIK of course. Eric emphasized an interesting statement in his article too, he said:

I emphasize that the logical sequence is well-defined because the compiler, jitter and processor are all allowed to change the actual order of events for optimization purposes, subject to the restriction that the optimized result must be indistinguishable from the required result in single-threaded scenarios.

The compiler or the Jitter or the processor are all able to modify the logical sequence for optimization purposes. The optimization shouldn’t affect the output in a single-threaded application, however, in a multi-threaded app, it might be observable. Yeah I see. I still don’t know why is this working this way? When exactly the increment is happening?

What do you think dear reader?

Please help me clarify the facts, and eliminate these confusions.

Yeah, I’m back.
I know it’s been a long time since I made my last blog post. Actually there’s no reason why I stopped blogging -besides being lazy of course. However, I’m back, and I’m back with big news. As you’ve read, the title of this post, is Google announced Chrome OS! -see the exclamation mark? I’m not going to claim -like others- that I was not shocked, actually I was. Why yet another operating system, ain’t Mac, Linux, and Windows enough already? Actually there have been a lot of explanations of this call of Goolge, since yesterday. Kent Beck wrote an interesting article about his vision of Chrome OS. Actually Kent’s article is very interesting -I’m sure you can judge that by reading only the title “Chrome OS is Worse, That’s the Point”. Kent, started his discussion with Chrome -the browser, it’s important to be specific from now on:). He mentioned that Chrome’s advantages overweights the disadvantages so that he uses it.


So I decided to try it, to simulate using Chrome as my operating system. I made it my default browser (in spite of Microsoft’s periodic attempts to change my preference) and expanded it to full screen. From then on I did everything I could on the web.

The key idea here -according to Kent- is that, It doesn’t matter if the new invention is better or worse, what matters is the alternatives that this new invention provides for people to do things they care for (I think email, and all web-stuff in general is something most people care for nowadays.


Innovations that start out worse need to be better at something new that matters. Imagine never having to install an application again. Never having to back up. Never having to reinstall the OS because it’s just gotten way too weird. I’d give up a lot to gain that. That was the point of telling you about my experiment: I’ve seen the future and it’s not so bad.

And here’s what Kent thinks MS, Apple, and Linux should do to stay strong on the desktop world:

To remain strong in desktop operating systems, though, Apple or Microsoft or the Linux desktops would have to abandon their current profit model, find a fresh ultra-simplification twist, and run the new business far from rational-but-doomed headquarters (Merlin, Oregon has a lovely abandoned sawmill site ready for development, in case you’re interested). They aren’t likely to do so, though, because it makes no sense

The question about the potential success or failure of Google Chrome OS will remain alive till a long time: -as Google Chrome OS will be shipped only later next year. I’m not sure! What do you think dear reader?

Anonymous Methods and Lambdas.

Posted by: Ahmed on: January 10, 2009

A while ago, when I posted my last post on this blog which was titles (Delegates and Events – A Look Back), I stated that it was an introduction to Lambda Expressions. Though it took me more than a month to re-blog again, here i’m continuing the journey on the C# 3.0 language enhancements features. The first thing we will discuss here is anonymous methods, as you know anonymous methods is just a shorthand way for subscribing to events and providing handlers all in one shot. The following code example shows the old way to subscribe to a Click event on a normal System.Windows.Forms.Button object.

code1

This is the very classic way of subscribing to event. You simply need to provide a pre-defined delegate (in this case EventHandler) that points to a function matching a specific signature (in this case returns void and accepts two input parameters an System.Object parameter, and System.EventArgs parameter) . Using anonymous methods, life can be easier. Check out the next code sample.

code2

As you can see here, all I needed to do in order to subscribe to the Click event on the Button object is to simply write my code that handles the event without having to define a whole new function just to handle this event, and also without having to know the event’s delegate signature.

Lambdas

Lambda expressions are another new way in C# 3.0 to substitute delegates in certain places. Now consider the following example, if you have a List<int>  and you want to filter this list and get only all the odd numbers out of it. One solution that might come handy is to use the FindAll method of your generic List<int>. FindAll expects one argument which in fact is of type System.Predicate<T>. System.Predicate<T> is a delegate that can point to any methods returns bool and takes a single argument T. The point is when FindAll was designed it was designed as this(take each item, check it, and then tell me if it should be included in the result set of the call).

The follwoing example illustrates the use of the smart FindAll method, take a look:

code3

As you see here I’ve defined a method called IsOdd that takes a single integer parameter and returns a boolean value indicating whether the passed in parameter is odd or not. I then called the FindAll method on my list of integers (numbers) passing in a new Predicated delegate that points to IsOdd. What is going to happen here is my numbers list will take each element of it and pass it to the IsOdd(the method that the Predicate delegate points to) and check the value returned, if true, then the item will be added to the result set. If false then the item will be ignored. If you run the above code you will get the following result.

code41

Now, what if you don’t want to define this whole IsOdd method that makes a really tiny job here and will not be reused by any other peace of code? Well, you guessed it, use anonymous method syntax like this:
code5

A lambda expression is another handy way for providing an anonymous method. The syntax might seem clumsy at first, but once you get it, you never quit it ;)

code6

What you see here is a lambda expression in action. The FindAll method expects a delegate and this time instead of passing it a delegate or an anonymous method I passed in well, a lambda, a lambda that will operate on one single integer parameter and return the the result of the expression x % 2 != 0.
The thing that most people find uncomfortable about lambdas is that, they can’t pronounce it, yeah, they write it but they can’t pronounce it. Our above example will be pronounce as follows (My only parameter will be processed this way “as what between the {} stats”).
A lambda expression can be in one of two forms; a single line form and a code block form. In our example we wrote a single statement in between two curly brackets, in fact I could have wrote any number of statements as needed. I will show you how lambda expressions can be appeared in a single line form:
code7

Well that’s it for lambdas, any questions or suggestions feel absolutely free to leave a comment.

Delegates and Events – A Look Back.

Posted by: Ahmed on: December 11, 2008

Every .NET programmer has used delegates in a way or another and hopefully appreciated the flexibility delegates provide. A delegate is simply a type-safe, object oriented function pointer. A pointer that can points to a function and can be used to dynamically invoke methods. Take a look at the following example on how to use the old fashion function pointer.

#include <iostream>

using namespace std;

 

//Function prototypes.

int Add( int, int) ;

int Subtract ( int, int);

 

void main( void ) {

 

int firstNumber = 0;

int secondNumber = 0;

int result = 0;

char answer = ‘a’;

//The declaration of function pointer.

int (*funcPtr) (int, int);

 

cout << “Plz enter the first number !” << endl;

cin >> firstNumber;

cout << “Plz enter the second number !”<< endl;

cin >> secondNumber;

 

cout << “Add or Subtract (A/S) ?” << endl;

cin >> answer;

 

if(answer == ‘a’)

funcPtr = Add; // Assigning a function to the pointer.

else

funcPtr = Subtract;

//calling the function using the function pointer.

result = funcPtr(firstNumber, secondNumber);

 

cout << “The result is “ << result << endl;

getchar();

}

//actual functions implementation.

int Add( int x, int y) {

return x + y;

}

 

int Subtract( int x, int y) {

return x – y;

}

That’s a complete C++ program to demonstrate the use of a function pointer. As you can see I’ve declared a function pointer funcPtr that is ready to point to any function that returns integer and takes two integers as parameters.

int (*funcPtr) (int, int);

After declaring the pointer and prompting the user for input, it’s now time to assign a value to this pointer. As this pointer is declared to point to function, so the value assigned to it is a function. The syntax used to assign a value to the function pointer is:


PointerName = FunctionName; (i.e. funcPtr = Add;)

Now we have everything set, the function pointer is declared and is pointing to a valid function. We can now call that function using that pointer name (remember pointers are variables that holds the memory address of other variables or functions on the program, and can be used to indirectly access those variables values or call the target functions.) as follows:

result = funcPtr(firstNumber, secondNumber);

This line is used to indirectly invoke the method that funcPtr is pointing to and passing in two integer variables (firstNumber and secondNumber) and also holding the function’s return value in yet another integer variable called result. The benefit of using this technique (regardless of the clumsy syntax) is that you can determine function calls according to user input in a concise way. Delegates basically do more or less the same job but in a more cleaner way. If you took a look at the above example (specially at this line
int (*funcPtr) (int, int);) you would notice that I have declared a function pointer funcPtr that can point to any function that returns integer and accepts two intger parameters. The dangerous thing about that line is that, I have not initialized that pointer which makes it poiting to a random place in memory and if I called it right a way without assigning a value to it, it would most probably cause my program to crash. (PS: you can use the following syntax to initialize that pointer to NULL at first declaration
int (*funcPtr) (int, int) = NULL;).

If you tried to use that pointer (funcPtr) before assigning value to it, the compiler will simply let you go, it will not generate an error to warn you from the potential risk. This is the real bad thing about function pointers and pointers in general, they’re flexible and powerful, but they are NOT safe.

A delegate is a safe, object-oriented replacement to the old function pointer. You can use delegates to indirectly invoke methods both in synchronous mode and asynchronous mode. As you may know delegates in C# are types, like classes, interfaces, structs and enums. They can be declared on a namespace level so you can reuse them in all the types in that namespace and mybe even across namspaces inside the boundary of one assembly or cross assemblies. To declare a delegate you use the following syntax.

public delegate int BinaryDel(int x, int y);

Here we declared a delegate (modern function pointer) called BinaryDel that can point to any method that returns an integer and takes two integer parameters. To put this delegate in action take a look at the following example:

class Program {

static void Main(string[] args) {

//Instantiating a new BinaryDel object

BinaryDel myDel = new BinaryDel(Add);

int result = myDel(5, 6);

Console.WriteLine(“The result is {0}”, result);

Console.ReadLine();

 

}

 

static int Add(int x, int y) {

return x + y;

}

 

static int Subtract(int x, int y) {

return x – y;

}

}

As you can see here, the first thing I’ve done in order to use this BinaryDel is to instantiate a new instance of this delegate using the new keyword and passing in a method name in the constructor. This is the name of the method that myDel (the instance of BinaryDel) will be pointing to. For now delegates do not have a lot to offer more than function pointer except for the type-safety that is provided through the compile-time check. Delegates are more than that, a delegate can point to more than one method and invoke them all respectfully. Each delegate itself is a class that extends the System.MulticastDelegate class, this class has a collection called invocation list which is a collection of .. well .. delegates. You can use the (+=)operator on any instance of a delegate to add method addresses to that invocation list and later then you can call them all.

class Program {

static void Main(string[] args) {

//Instantiating a new BinaryDel object

BinaryDel myDel = new BinaryDel(Add);

myDel += new BinaryDel(Subtract);

myDel += Multiply;

 

int result = myDel(5, 6);

Console.ReadLine();

 

}

 

static int Add(int x, int y) {

Console.WriteLine(“Inside Add method”);

return x + y;

}

 

static int Subtract(int x, int y) {

Console.WriteLine(“Inside Subtract method”);

return x – y;

}

static int Multiply(int x, int y) {

Console.WriteLine(“Inside Multiply method”);

return x * y;

}

}

That’s an update to the first example. In this example I’ve updated the Add and Subtract methods to print a line to the console indicating that each of them has been called. I also added a brand new method called multiply that also returns an integer and takes two integer parameters (i.e. matches the delegate signature.)I then used the += operator to add both Subtract and Multiply methods to the invocation list of myDel. Now myDel points to three methods Add which is passed to it in the constructor, Subtract, and Multiply that are added to it using the += operator.


PS: when using the += operator on a delegate instance, it expects another instance of the same delegate to be added to the invocation list of the left side delegate of the assignment. So at the first time I used the syntax (myDel += new BinaryDel(Subtract);) to add new instance of BinaryDel pointing to Subtract to the invocation list of my current instance myDel, this is the expected behavior because as you may recall I mentioned that each delegate’s invocation list is simply a list of the same delegate items, each of which points to one or more methods. However, the syntax I used next is different than that
(myDel += Multiply;). This is the same as the previous syntax. The compiler here will create a new instance of BinaryDel pointing to Multiply and then will add that instance to the invocation list of myDel. It’s also worth mentioning that you can remove method addresses from any delegates invocation list using the -= operator. Consult the .NET framework documentation for more details.

When calling these methods using myDel like so myDel(5, 6); they will be called in order meaning that the Add method will be called first then the Subtract then the Multiply (you may know guess that the invocation list of myDel is implemented as a Queue .. smart cookie J ). Now the question is “What is the value of result?” the answer is “The value of result is the return value of the last method in the invocation list, in our case multiply.

One more feature of delegates is that they provide the ability to invoke methods asynchronously throught the delegates bulit in method BeginInvoke. BeginInvoke will invoke the methods on a new background thread, and the main thread will keep executing at the same time, then when you are ready to receive the return of that method you called by the delegate you can call EndInvoke on the very same delegate. You can also provide an AsyncCallBack delegate that point to some method –Say A- as a parameter to begin invoke, this method –A- will be called automatically after the execution on the background thread ends. or further details consult the .NET framework decumentation.

Delegates can also be used as function parameters and function return types. However, the primary usage for delegates in the .NET universe is to subscribe to events. An event is a flag raised by an object to indicate the various phases of the object life cycle. Assume we have a class called Employee that represents an actual employee. We will use events to flag some key time-points in the employee life cycle, points like when the employee gets hired or when picked for an external mission or when he or she gets fired. The code for the employee class my more or less look like this:

//Custom delegate to use for the employee events.
public delegate void EmployeeDel(Employee e, string action);

 

public class Employee {

//Creating the events.

public event EmployeeDel OnGettingARaise = null;

public event EmployeeDel OnPromoting = null;

 

public int Age { get; set; }

public float Salary { get; set; }

public string Name { get; set; }

public string Position { get; set; }

 

public void ShowDirectMangerSomeLove() {

Console.WriteLine(“EMployee>> Mr Manager .. you’re the best :) .. !”);

Console.WriteLine(“Manger>> thanks {0} you got a raise !”, this.Name);

//Increasing the salary by 5

this.Salary += 5;

//Raising the event if there are any subscribers.

if (OnGettingARaise != null)

OnGettingARaise(this, “Having a raise”);

}

 

public void ShowCEOSomeLove() {

Console.WriteLine(“>>Employee: Mr CEO .. You’re leading us right to the top”);

Console.WriteLine(“>>CEO: thanks {0} .. you know what .. I really think you should be in a higher position”, this.Name);

this.Position = “Manager”;

this.Salary += 200;

//raising the event if there’s any subscribers.

if (this.OnPromoting != null)

OnPromoting(this, “Got promoted !”);

}

}

Here I have declared a custom delegate called EmployeeDel that can point to any method that returns void and takes an Employee and a string as parameters. Then inside the Employee class declaration I created two events OnGettingARaise and OnPromoting, both using the EmployeeDel delegate. In the ShowDirectManagerSomeLove() method I raise the OnGettingARaise event passing in the current object and a string indicating that the employee has a raise, I then increase the employee’s salary as a result of showing his manager some love J. As you notice here because the OnGettingARaise event is declared of type EmployeeDel, it has to pass in the required parameters for this EmployeeDel (Employee, string) when it’s being raised. To see this Employee class in action, take a look at the following:

class
Program {

static void Main(string[] args) {

Employee shankl = new Employee() {

Name = “Shankl Shankool”,

Age = 30,

Salary = 2000f,

Position = “Sales Man”

};

 

shankl.OnGettingARaise += new EmployeeDel(HandleEmployeeGettingARaise);

shankl.ShowDirectMangerSomeLove();

 

}

static void HandleEmployeeGettingARaise(Employee e,

string action) {

Console.WriteLine(

“{0} who works as {1} has got a raise .. \nhis salary now is {2}”,

e.Name, e.Position, e.Salary);

}

}

The program class containing the Main method defines a method called HandleEmployeeGettingARaise that matches the EmployeeDel delegate singuature as it returns void and takes two input parameters (Employee, string). This method can be used to handle the OnGettingARaise and OnPromoting events for the employee class as it matches the type of these events (EmployeeDel). In Main I’ve declared a new Employee with the name “Shankl Shakol” and 30 years of Age and 2000$ salary and works as a “Sales Man” using the object initializaiton syntax. The next line is the line where I subscribe to the OnGettingARaise event of the Employee object-shankl-and provide delegate of the type EmployeeDel that points to my HandleEmployeeGettingARaise method. This means that when this event is raised my handler (HandleEmployeeGettingARaise mehtod) will be executed. Run the code and examine it yourself.

As a person who develops applications for business, there’s no doubt that most of the times you have to create classes that hold nothing but data –Which you most of the times would get them generated some way or another). Now imagine that you have a class called EmployeeData which is designed to hold only data of employees. This class can more or less look like the following.

class EmployeeData {

//Member Variables.

private Guid id;

private string name;

private int age;

private string address;

private float salary;

private string position;

 

//Public access properties.

public Guid ID {

get { return this.id; }

set { this.id = value; }

}

}

As you can see here, you define the class variables as private and then encapsulate them in properties to enforce some business logic on the access of these variables. However, most of the times your properties don’t have any business logic code or validation in either of their Getter or Setter accessors. Though the properties are totally useless in this case, you still have to implement them just to have the OO look. Auto Implemented Properties is a capability added to C#3.0 and higher to save you some keystrokes (actually a lot of key strokes). If you have to implement a property to provide access to a variable in your class without having any code to run while getting or setting a value to this variable, use auto implemented property as follows.

public Guid ID { get; set; }

public string Name { get; set; }

public int Age { get; set; }

In the following code, I’ve declared three public properties ID, Name, and Age. I took advantage of the auto implemented properties syntax and saved my self some keystrokes by simply not adding a get and set bloc(though the accessors themselves already exist). The magic part here is the “;” semicolon after the get and the set accessor; this semicolon indicates that the compiler will automatically generate a private field with the type of the property (System.GUID, or System.String, or System.Int32 in our case) and will have the get and set retrieves and sets a value to that automatically generated variable. It worth mentioning that you can’t reference this variable directly, you have to use the property to access it. Also the name of this automatically generated variable is a really compiler-kina names (e.g. “x3ydfa34343adfa343″). The auto implemented properties syntax does not add any magic to your code, it simply saves you some keystrokes by instructing the compiler to generate a variable to you and allows access to this variable through your properties.

2- Object Initialization Syntax.

As an OO programmer, creating objects is a huge part of your daily job duties. You most of the times instantiate new objects of your classes or the base library class to work with and mainpulate in order to get your task done. C# 3.0 added a new capability for programmers to easily create instances of objects with different state. For example if you are creating an employee object named John Doe with 25 years of age and works as a Sales Representitive; your code will look like this :

EmployeeData e = new EmployeeData();

e.Name = “John Doe”;

e.Age = 25;

e.Position = “Sales Representative”;

 

As you can see, it took you 4 lines to create one employee instance. In order to avoid the hassle and save ourselves some time when creating employees we may create some overloaded constructors in the EmployeeData class and instantiate objects using these custom constructors like so:

public EmployeeData(string name, int age, string position) {

this.Name = name;

this.Age = age;

this.Position = position;

}

//Instantiating an object using the custom constructor
EmployeeData x = new EmployeeData(“John Doe”, 25, “Sales Representative”);

Obviously this saves a lot of keystrokes, precisely 3 lines for each employee. As you can see her the way to get to this was by editing the definition of the EmployeeData class itself. Now the question is How can I achieve this if I don’t have the class source code? Well the answer is-you guessed it-Object Initialization Syntax.
Object initialization syntax allows you to create objects with different state(i.e. different values of properties and public variables) quickly and easily. You simply create the instance of your object followed by a comma delimited list of public fields enclosed by two curly brackets ({ }). So instantiating the same John Doe employee using object initialization syntax would look like the following:

EmployeeData x = new EmployeeData() { Name = “John Doe”, Age = 25, Position = “Sales Representatives” };
ps: you have to define a default constructor in the EmployeeData class in order for the above line to work.

You can also call a custom constructor and then use the object initialization syntax afterwards like so:

EmployeeData x = new EmployeeData(“John Doe”, 25, “Sales Representative”) { ID = 1 };

In the above example we created the same john doe using the custom constructor then added object initialization syntax to the statement to include the id value to be one. Now the created object has the name “John Doe”, Age 25, Position “Sales Representative”, ID 1.

This last code example fires up the question “what is the order of these values?”. Consider the following example.
EmployeeData x = new EmployeeData(“John Doe”, 25, “Sales Representative”) {

Name = “Hussien IBS”,

Age = 45,

Position = “CO”,

ID = GUID.NewGuid()

};

Now if you printed out the values of x.Age, x.Name, and x.Position, what will the actual values be? Well one fact to know about object initialization syntax is that it works in order (i.e. x.Name will have the value “John Doe” by the custom constructor, then it will be assigned the value “Brack Belick” by the syntax that followed the constructor call. Bottom line here: Object initialization syntax gets executed in orderf from left to right.

Initializing Inner Types:
Let’s assume that we have another object in the system called Office like the following:

class Office {

public string OfficeType { get; set; }

public float OfficeArea { get; set; }

}

and the EmployeeData has an office object as a member of it. Take a look at the following code:
public Office MyResidence { get; set; }

You can use the object initialization syntax to initialize the inner type as well:
EmployeeData x = new EmployeeData() {

Name = “Husien IBS”,

Age = 45,

Position = “CO”,

ID = Guid.NewGuid(),

MyResidence = new Office() {

OfficeArea = 25.5f,

OfficeType = “Glass Office”

}

};

Collection Initializers:

Object initialization syntax allows you to use the array-like initializtion with your types as follows :

List<EmployeeData> enEmps = new List<EmployeeData>() {

new EmployeeData() {

Position = “Developer”,

Name=“Mohammed Kasem”

},

new EmployeeData() {

Position = “Developer”,

Name=“MOhamed Tolba”

}

};


<!–[if !supportLineBreakNewLine]–>
<!–[endif]–>

 

 

string name = “Ahmed Halwagy”;

if (name.IsHalwagy())

Console.WriteLine(“Yeap”);

else

Console.WriteLine(“Not halwagy”);

Shocked? .. Cool!
Now I assume that two questions just pumped into your mind:
1- What the heck is that IsHalwagy() method?
2- Would Microsoft ever -for any reason- reshape their string object to add this method?

I will answer your questions from bottom up. Question number 2, the answer is No. Though Microsoft really pursue my own satisfaction, but they never went this far -but I really encourage you to email the C# team and ask them for IsHalwagy() method on the string class(just kidding :) ).

Question number 1, the answer is: It’s my own method. I’ve extended the string class by this IsHalwagy() method, and believe it or not, I didn’t have to use classes from the System.Reflection.Emit namespace, actually the job was much easier(as easy as typing 3 lines of code J ).

Confused! That’s good. Now relax and take a deep breath.
As you know, C# types (classes, interfaces, delegates, structs, enums)once compiled into an assembly, they’re final, meaning that the only way to change them is to have their source code, edit it, and then recompile. However, this is not the case in C# 3.0; in C# 3.0 you can extend any compiled-final- .NET type using a very easy and convenient way through Extension Methods.

Though the usefulness of this capability is extremely obvious in the previous IsHalwagy() example, let’s consider a more useful scenario –at least more useful for you.
<!–[if !supportLineBreakNewLine]–>
<!–[endif]–>

static class IntOperations {

public static bool IsEven(int x) {

return (x % 2) == 0;

}

public static long Factorial(int x) {

if (x <= 1)

return 1;

else

return x * Factorial(x – 1);

}

}

 

In the previous example we have a class called IntOperations this class contains some of the operations than you would need to perform on any integer. The typical use for the methods in this class would be ass follows:

int x = 5;

Console.WriteLine(“The factorial of {0} = {1}”, x,IntOperations.Factorial(x));

Console.WriteLine(IntOperations.IsEven(5));

By using extension methods you can alter the previous example to use the Factorial(int) and the IsEven(int) methods as if they were originally built into the System.Int32 struct. The only change that is required in order to achieve that is to add 8 characters to your methods declaration, as follows:

static class IntOperations {

//Notice the this modifier precedding the parameter declaration.

public static bool IsEven(this int x) {

return (x % 2) == 0;

}

public static long Factorial(this int x) {

if (x <= 1)

return 1;

else

return x * Factorial(x – 1);

}

}
Here all I’ve done is simply adding the “this” modifier before the first parameter of each method declaration. Adding the “this” modifier to the declaration of the int parameter simply instructs the compiler to deal with method as if it was originally built into the System.Int32 type.Voila! that’s it. By doing so you can simply call your methods on any instance of type System.Int32 as if it was originally coded into it:

int x = 5;

Console.WriteLine(“The factorial of {0} = {1}”, x, x.Factorial());

Console.WriteLine(x.IsEven());

Now let’s take alook at what’s really happening behind the scens. If you compile this project and open the assembly using a tool like (ILDASM) you will find that the compiler is invoking the static methods in a very normal manner (i.e. IntOperations.Factorial(x)). What you really saw of x.Factorial() is just some smoke-and-mirror effect. Here’s a part of the IL viewed by IlDASM for this assembly:

 

.method private hidebysig static void Main(string[] args) cil managed

{

.entrypoint

// Code size 44 (0x2c)

.maxstack 3

.locals init ([0] int32 x)

IL_0000: nop

IL_0001: ldc.i4.5

IL_0002: stloc.0

IL_0003: ldstr “The factorial of {0} = {1}”

IL_0008: ldloc.0

IL_0009: box [mscorlib]System.Int32

IL_000e: ldloc.0

IL_000f: call int64 ConsoleApplication3.IntOperations::Factorial(int32)

IL_0014: box [mscorlib]System.Int64

IL_0019: call void [mscorlib]System.Console::WriteLine(string,

object,

object)

IL_001e: nop

IL_001f: ldloc.0

IL_0020: call bool ConsoleApplication3.IntOperations::IsEven(int32)

IL_0025: call void [mscorlib]System.Console::WriteLine(bool)

IL_002a: nop

IL_002b: ret

} // end of method Program::Main

 

 

Ps: the compiler calls the extension methods statically using their clas names.

 

Extension Methods Restrictions:

<!–[if !supportLists]–>1- <!–[endif]–> EExtension methods must be declared in static class, and there for they must be static as well (remember static classes can only contain static methods, and static fields).

<!–[if !supportLists]–>2- <!–[endif]–> Normal object instance methods take precedence over extension methods if they happened to be with the same signuature.

 

Importing namespaces containing types that define Extension Methods:

Namespaces containing the classes that contain extension methods have to imported in order to be able to use the extension methods defined on them.
Let’s take a while discussing this poing, now consider that my IntOperations class is declared inside a namespace called MyEXTNamespace, and the program class containing the main method is declared inside a namespcae called MyAssemblyNamespace. The code will look like the following.
using System;

using System.Linq;

namespace MyAssembly {

class Program {

static void Main(string[] args) {

int x = 5;

Console.WriteLine(“The factorial of {0} = {1}”, x, x.Factorial());

Console.WriteLine(x.IsEven());

}

}

}

namespace MyEXTNamespace {

static class IntOperations {

//Notice the this modifier precedding the parameter declaration.

public static bool IsEven(this int x) {

return (x % 2) == 0;

}

public static long Factorial(this int x) {

if (x <= 1)

return 1;

else

return x * Factorial(x – 1);

}

}

}

If you try to compile this code you will get compile time errors indicating that System.Int32 does not containg a definition fo IsEven() and Factorial(). Can you see it? Can you see the problem?

The problem is you declared your extension methods in MyEXTNamespace and in order to use these methods outside the scope of this namespace you have to import this namespace by adding a using directive to MyEXTNamespace namespace at the top of your file as follows:

using MyEXTNamespace;

Problem Solved!

 

Using Extension Libraries:

Now as you can see it can be very useful if you are able to use your extension methods in many projects as any other .NET library. This is absolutely possible. You can simply move your MyEXTNamespace namespace to another class library project and build this library and simply reference the output assembly from any other .NET project and reuse. Just remember to mark the classes containing the extension methods with the public access modifier in order to be used cross assemblies.

 

A Final Detail:

One last thing you should know about extension methods is that they apply to inheritance concepty i.e. if you extended a parent class with some method, all the derived classes will inherit this method. Take a look at the following example:

public static string ReturnYourParentType(this object o) {

Type t = o.GetType();

if (t.BaseType == null)

return “Don’t have a parent, I’m object”;

return t.BaseType.FullName;

}

 

Here I’ve extended the System.Object class with a method that returns the name of the parent type of any object. Now watch me invoking this method:

 

object o = new object();

Console.WriteLine(o.ReturnYourParentType());

 

int x = 5;

//it applies to int too. because int is an object.

string intParent = x.ReturnYourParentType();

Console.WriteLine(“intParent = {0}”, intParent);

// and applies to string too. again because string is also an object.

string stringParent = “hello”.ReturnYourParentType();

Console.WriteLine(“stringParent = {0}”, stringParent);

 

As you can see here I’ve invoked this method on any thing of type object, and of course in .NET every thing is an object. So because every thing inherits from object, I can call my ReturnYourParentType() on any thing.

 

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

Posted by: Ahmed 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.


 

 

Calendar

January 2012
S M T W T F S
« Nov    
1234567
891011121314
15161718192021
22232425262728
293031  

Categories

Delicious

Recent Twitter Updates

Follow

Get every new post delivered to your Inbox.