Ahmed El-Halwagy’s Blog

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




string name = “Ahmed Halwagy”;

if (name.IsHalwagy())



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

static class IntOperations {

public static bool IsEven(int x) {

return (x % 2) == 0;


public static long Factorial(int x) {

if (x <= 1)

return 1;


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));


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;


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());


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



// 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,



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());





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;


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();



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.


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) {




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

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



Yeah 🙂 I finally had a blog.

Two months ago I started to seriously think of having a web blog, as a way to express my thoughts online. So, I came to different options. Like building my own blog from scratch which is quite un applicable right now. coz building an effective, fully-featured blog is certainly a time consuming kind of job, and for someone who’s busy as hell just like myself here, is typically too difficult. So I went to another direction and thought, well maybe I can use WSS to build an effective blog quickly and easily. So I started to hit google and search for web hosts that support WSS and ofcourse I found way to many to many that will host any WSS content for me but none of them was free. So instead of being dispeared and let the idea of having a blog disappear -at least temporarly- from my mind, I accepted the solution of having a public blog on some blogging sites like MySpace or the one i’m using here WordPress. So I chose to start something -even a silly thing- better than waiting long time to start the perfect thing.


July 2018
« Nov    



Recent Twitter Updates