Ahmed El-Halwagy’s Blog

Archive for the ‘C# 3.0’ Category

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 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.

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]–>

 

 


Calendar

August 2017
S M T W T F S
« Nov    
 12345
6789101112
13141516171819
20212223242526
2728293031  

Categories

Delicious

Recent Twitter Updates

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