Feeds:
Posts
Comments

Posts Tagged ‘C# 4.0’


[tweetmeme  source=”aabdulmoniem” only_single=false]

I have just finished “Beginning Silverlight 4 in C#” book written by Robert Lair from Apress and I would like to share my humble opinion about it.

Really and simply, it is a great book to grasp many concepts about Silverlight 4 in a just 400 papers. For me, I have finished the book in four days (3-5 hours / day) and of course there are some reasons for that, a couple of them are:

  1. I am not so beginner in this technology as I have used WPF before so I didn’t need any time to grasp multiple concepts quickly.
  2. I need to finish this book as quickly as possible to wrap most of the features and abilities of the new version of Silverlight. In fact my team is going to develop a business application using Silverlight and I was in real need to see the full picture of this technology.

Enough talking about myself, let’s talk about the book.

This book talks about:

  • Why we need Silverlight and how it fits in the RIAs? Really a good and brief introduction gives the reader why he is gonna read about such a new technology.
  • VS 2010 new features and how it supports Silverlight 4 and what you need to get started. BTW, there are some posts here in my blog about the new features of VS 2010 you can find it in “Cutting Edge” column.
  • Layout management in Silverlight. It mentioned some of layout controls and how you can use it to layout your applications like the Grid, WrapPanel, DockPanel, Canvas, and StackPanel.
  • Some of Silverlight controls and some basic examples about them like TextBox, Button, TextBlock … etc.
  • List controls like DataGrid and ListBox besides data binding mechanisms which is so so powerful in the world of XAML.
  • Silverlight toolkit, and what it contains.
  • How you can get access to data in Silverlight (WCF is recommended approach), how you can use Sockets for data access and network communications.
  • Navigation framework which is so similar to master pages and content place holders in ASP.NET. Also, how you can pass data between different pages, how you can map the URIs, and How you can route the URIs to custom ones.
  • Isolated storage and how you can use it for caching purposes, saving and retrieving files … etc.
  • Accessing computer devices like web cam and microphone from a Silverlight application easily.
  • Expression blend introduction and how it fits in the world of Silverlight.
  • How you can style your application in a very similar way to CSS in HTML pages.
  • How to animate objects easily and how to use Expression Blend for this purpose with some basic and nice examples.
  • How to create custom controls, although the book didn’t mention how to create user controls. It gives a very good example for building a custom control from scratch.
  • How Printing is so easy in Silverlight. You can print the screen as it is, or you can even customize the printable data to select portions of screen or even a whole new shape.
  • Finally, it talks briefly about important concepts and ideas you will need when you need to deploy a Silverlight application. It gives an idea about assembly cashing, out-of-browser mode, and elevated trust.

Really, I am recommending this book to any one who needs really to know what is the Silverlight about and what can do.

Thank you Apress for not wasting my time 🙂

    Read Full Post »


    [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!

    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 »