Feeds:
Posts
Comments

Posts Tagged ‘c#’


[tweetmeme source=”aabdulmoniem” only_single=false]

Another new feature in C# 4.0 is covariance and contravariance. Really, I will let you in this post with those two nice videos which explains well what is this new feature. This video is made by Eric Lippert divided into two parts. Enjoy!

How Do I: Use Covariance and Contravariance in VS 2010 Part I?

How Do I: Use Covariance and Contravariance in VS 2010 Part II?

I really do like the new feature because it didn’t break the main theme of C# that is strongly typed language.

Also, I like the semantics behind the in and out keywords when used in this new feature.

Finally, I don’t have to cast each element in IEnumerable sequence coming from LINQ to return a sequence of some related class, it will be done for me at compile time out of the box! Great!

Advertisements

Read Full Post »


[tweetmeme  source=”aabdulmoniem” only_single=false]

If we look at the theme of C# 3.0 – 3.5, we will see that functional programming has been introduced by exposing LINQ features.

And if we look into the current release theme, we will see that this year’s theme is dynamic keyword.

Dynamic keyword gives you the ability to create objects dynamically at runtime, gives you the ability to call something you already know that it is existing but at runtime not at compile time, and it gives you the ability to interact with dynamic languages such as python for example.

Let’s get started with this new keyword.

Assume that we have the following Person class:

public class Person
{
     public string Title { get; set; }
     public string FirstName { get; set; }
     public string LastName { get; set; }
     public string FullName
     {
         get
         {
             return Title + " " + FirstName + " " + LastName;
         }
     }

    public Person()
    {
    }

    public Person(string title, string firstName, string lastName)
    {
         Title = title;
         FirstName = firstName;
         LastName = lastName;
    }

    public void Print()
    {
         Console.WriteLine(FullName);
    }
}

In the Main method of a console application, if I would like to instantiate a new object from the Person class I would do this:

Person person = new Person();
person.Title = "Mr.";
person.FirstName = "Ahmed";
person.LastName = "Abdul Moniem";
Console.WriteLine(person.FullName);

In the last example, the compiler at compile time knows exactly what is Person is and what its type. So, it will generate error if you tried to access a non-existent property or method in the Person class.

Lets add couple of lines to demonstrate the dynamic type:

Person person = new Person();
person.Title = "Mr.";
person.FirstName = "Ahmed";
person.LastName = "Abdul Moniem";
Console.WriteLine(person.FullName);

dynamic dynamicPerson = person;
dynamicPerson.FirstName = "Mohamed";

Console.WriteLine(dynamicPerson.FullName);

As you can see, I have created a new variable called dynamicPerson and its type is dynamic which telling the compiler that it will be validated at runtime. In last example, I have made dynamicPerson to point to person object then I have changed a property on the dynamicPerson and used it to print the full name on the screen.

The same results between this and the normal object initiation process. So, what is the benefit of dynamic keyword?

Let’s add the following using statement on top of our file like that:

using System.Dynamic;

And in our Main method we will write something like that:

dynamic employee = new ExpandoObject();
employee.FirstName = "Ahmed";
employee.LastName = "Abdul Moniem";
employee.FullName = employee.FirstName + " " + employee.LastName;
Console.WriteLine(employee.FullName);

Here is the magic of dynamic keyword, you can create a new object which doesn’t exist at all at runtime. In the last example we have created a new employee of type ExpandoObject (in System.Dynamic) which supports this dynamic behavior in the language.

While I was coding I realized that an employee must have a first name so I wrote:

employee.FirstName = "Ahmed";

And again I realized that the employee must have a last name, so I wrote:

employee.LastName = "Abdul Moniem";

As you may guess, I also realized that I want to add a new property FullName, so I wrote:

employee.FullName = employee.FirstName + " " + employee.LastName;

Then I print the result, and viola! every thing is working exactly as the first example of Person class in this post despite of that I don’t have any employee classes! This is the magic of dynamic keyword.

Let’s add some sugar on my employee object:

employee.Print = new Action(delegate() { Console.WriteLine(employee.FullName); });
employee.Print();

As you can see, I have added a new method which will run at runtime without any mentioned error, also at compile time everything is working fine as long as I am using this dynamic keyword.

You can also, use the famous lambda expression to create your methods. So, the last example can be changed to be:

employee.Print = new Action(() => Console.WriteLine(employee.FullName));
employee.Print();

Until now, I am just demonstrating some of the capabilities of this new keyword but until now I didn’t reveal its power!

Let’s now consider some real cases. What if I have a type which I want to instantiate an object from it at runtime and then call a method on this object still at runtime. This means that I don’t know that type at compile time. This means I have to use reflection, my old friend.

// Assuming that Person type is not known until runtime
Type t = typeof(Person);
object person = Activator.CreateInstance(t, null);

The method CreateInstance will return a type object not a Person type. Which means I can’t do this:

// Compile time error, no method named Print() in object!
person.Print();

So, what I have to do? I should use Invoke method to call the Print method at runtime. The reflection engine at runtime will know that I have a person object that I can call Print on it, and it will call it on behalf of me.

t.InvokeMember("Print", System.Reflection.BindingFlags.InvokeMethod, null, person, null);

And here is the complete code:

// Assuming that Person type is not known until runtime
Type t = typeof(Person);
object person = Activator.CreateInstance(t, null);
t.InvokeMember("Print", System.Reflection.BindingFlags.InvokeMethod, null, person, null);

Using the dynamic keyword, it becomes more easy and cleaner to develop a scenario like this:

// Assuming that Person type is not known until runtime
Type t = typeof(Person);
dynamic person = Activator.CreateInstance(t, null);
person.Print();

Let’s now delve into a more interesting topic, how you can run a dynamic language like python from C#?

First of all, you will need to install IronPython and reference its assemblies into your project.

Now we will write a simple python script into a file called Math.py for example, and it to your project root and it must have Copy Always value of its Copy to Output Directory property:

def Add(x ,y):
    return x + y

Now we will execute this python script:

var py = Python.CreateRuntime();
dynamic test = py.UseFile("Math.py");
dynamic sum = test.Add(5,10);
Console.WriteLine(sum);

And simply you will see the result 15 printed on the screen! Nice, right?!

Finally, I have just highlighted some of the features of this dynamic keyword and how you can use it in many different scenarios. I hope you all to grasp all the benefits of this new keyword.

Read Full Post »


[tweetmeme  source=”aabdulmoniem” only_single=false]

One of the new features of C# 4.0 that I liked so much is: Named and Optional Parameters. This feature simplifies the old concept method overloading or constructor overloads.

Also, It makes your code more cleaner and concise. Also, you will not be obligated to duplicate code in many method overloads in order to achieve the same functionality which in return improves maintainability of your application.

And a big enhancements in the COM land while using optional parameters because it will not obligate you to enter all the arguments coming from a COM interface which is often too large number of arguments.

Let’s first demonstrate the old days of C#. Consider that we have a simple class Person like the following:

public class Person
{
     public string Title { get; set; }
     public string FirstName { get; set; }
     public string LastName { get; set; }

     public string FullName
     {
         get
        {
            return FirstName + " " + LastName;
        }
     }

     public Person()
     {
         Title = "Mr. ";
         FirstName = "Ahmed";
         LastName = "Abdul Moniem";
     }

     public Person(string firstName, string lastName)
     {
          Title = "Mr. ";
          FirstName = firstName;
          LastName = lastName;
     }

     public Person(string title, string firstName, string lastName)
     {
          Title = title;
          FirstName = firstName;
          LastName = lastName;
     }
}

As you can see we have many overloads for the Person constructor. So, if you want to use the default constructor which initialize data members with the default values you can just use the default constructor but if you want to change one of the default data members you can use another overload.

Let’s consider here a deadlock example, assume that you want to create a new instance of Person class and you want only to change the default value of LastName property. You can create a new constructor overload that will satisfy your needs. It will take only last name and assign this value to the LastName property and we will keep all the default values in place in both Title and FirstName properties. It will be like this:

public Person(string lastName)
{
    Title = "Mr. ";
    FirstName = "Ahmed";
    LastName = lastName;
}

And we can create a new person object using this constructor like this:

Person person = new Person(“Abdul Moniem”);

Perfect! Ok, here is the deadlock, what if I want to do the same thing with first name. So, I will create another constructor overload like this:

public Person(string firstName)
{
     Title = "Mr. ";
     FirstName = firstName;
     LastName = "Abdul Moniem";
}

But unfortunately, this is not allowed. Overloading methods must defer in the number of parameters and/or types. So, we can’t put two constructors taking only one string parameter!

Even if you chose to use the last constructors which supplies all the data members to the object and you will put the default values by hand. This is not possible if you don’t know what is the default values (most of the cases, specially if you are not the creator of the class and you are just using it). Also, it is not a neat solution because you are always obligated to use all the arguments of the constructor!

Here the new Named and Optional Parameters feature comes to the rescue. We will modify the Person class to the following and naming it PersonEx (just for differentiation):

public class PersonEx
{
     public string Title { get; set; }
     public string FirstName { get; set; }
     public string LastName { get; set; }
     public string FullName
     {
          get
          {
             return Title + " " + FirstName + " " + LastName;
          }
     }

    public PersonEx(string title = "Mr. ", string firstName = "Ahmed", string lastName = "Abdul Moniem")
    {
        Title = title;
        FirstName = firstName;
        LastName = lastName;
    }
}

As you can see we have only one constructor that will satisfy our needs and this is the synatx of optional parameters in any method or constructor:

For each argument you are supplying the default value like this (Type ArgumentName = DefaultValue) like in (string Title = “Mr. “). This tells the compiler that this argument will be optional with a default value = “Mr. “.

This the part of optional parameters. What about the named ones?

When you want to create a new object from PersonEx you can do the following:

PersonEx person1 = new PersonEx(lastName: "Mohamed");
PersonEx person2 = new PersonEx(firstName: "Mostafa");
PersonEx person3 = new PersonEx(firstName: "Mostafa", lastName: "Mohamed");
PersonEx person4 = new PersonEx("Miss. ", "Mona", "Mansour");

as you see, the syntax of named parameters comes in the form of (ParameterName: ParameterValue) like in (lastName: “Mohamed”).

Deadlock is solved! right! you can use any combination you want without creating many overloads, and with super flexibility while creating objects.

A remaining important thing is that you are obligated to add the optional parameter at the end of the method header like param keyword. So the following syntax is wrong and it will give you a compile time error:

public PersonEx(string title = "Mr. ", string firstName, string lastName = "Abdul Moniem")
{
     Title = title;
     FirstName = firstName;
     LastName = lastName;
}

but this is correct, considering that firstName becomes a required parameter and the other two are optional (you can make methods hybrid):

public PersonEx(string firstName, string title = "Mr. ", string lastName = "Abdul Moniem")
{
     Title = title;
     FirstName = firstName;
     LastName = lastName;
}

Read Full Post »


[tweetmeme source=”aabdulmoniem” only_single=false]

Today, I am coming with a new useful tool which helps you do the following:

  • Save keystrokes and time
  • Simplify documenting your code
  • Benefit of the base class documentation

It is the GhostDoc:

GhostDoc is a free Visual Studio extension that automatically generates XML documentation comments for methods and properties based on their type, parameters, name, and other contextual information.

How you can use it?

  • For C#:

C# GhostDoc

  • For VB.NET:

VB.NET GhostDoc

Also, you can use GhostDoc using the GUI by right clicking any method or class that you want to document and just choose “Document this” which will generate all the proper XML documentation for you.

Document This - GhostDoc

Features

  • Generates XML comments based on code element type, parameters, name, and other contextual information.
  • For a derived class uses the base class documentation.
  • Assignable shortcut (default Ctrl-Shift-D)
  • Configurable rules, acronyms and macros
  • Import/Export of the configuration and the rules
  • Option to re-build documentation

It is now available for the following IDEs:

  • Visual Studio 2010 RC
  • Visual Studio 2008
  • Visual Studio 2005

Read Full Post »

%d bloggers like this: