Ahmed El-Halwagy’s Blog

Moved!

Posted 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! :)

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?

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?

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?

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.

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.

Calendar

September 2014
S M T W T F S
« Nov    
 123456
78910111213
14151617181920
21222324252627
282930  

Categories

Delicious

Recent Twitter Updates

Error: Twitter did not respond. Please wait a few minutes and refresh this page.

Follow

Get every new post delivered to your Inbox.