Sunday, November 23, 2008

C# 4.0 - Overcomplicated?

I've seen C# 4.0 draft and something came into my mind: is this language as simple as Microsoft used to advertise it? Let me show a few C# 4.0 features.

New C# 4.0 features

Dynamic types

  1: dynamic d = GetDynamicObject(…);
  2: d.M(7); // calling methods
  3: d.f = d.P; // getting and settings fields and properties
  4: d[“one”] = d[“two”]; // getting and setting thorugh indexers
  5: int i = d + 3; // calling operators
  6: string s = d(5,7); // invoking as a delegate

C# used to be a static language. Now you can create dynamic types as well.

Optional parameters

  1: public void M(int x, int y = 5, int z = 7){...};

x is mandatory. y and z are optional parameters.

Named parameters

  1: M(z: 3, x: 1);

COM interop

You have to set a cell in Excel now as follows:

  1: ((Excel.Range)excel.Cells[1, 1]).Value2 = "Hello";

In C# 4.0 you can do this thanks to dynamic types:

  1: excel.Cells[1, 1].Value = "Hello";

The need for language improvements

If you look at C# improvements like generics, var, anonymous methods, dynamics etc., we can see big needs behind them. The main reasons are LINQ and COM interoperability improvements. If you know these 'extensions', you can imagine the complexity of LINQ without e.g. var.

Implications

Can you remember Perl? It used to be a very promising (scripting) language. You can code/talk Perl on very different levels (I love Perl for this :)). If you don't know that specific level (expressions), you can hardly read/write that code. An example:

  1: print "Hello, world!\n";

or

  1: say 'Hello, world!'

Does C# walks the same path? Introducing dynamic types to a basically static language, introducing optional and named parameters to a C(++)-like language. I love changes, but these can generate problems.

You can't use e.g. generics at certain companies because some programmers don't understand them (maybe it's not the best example but I hope you can get my idea).

Can you or do you read/write all the following C# 3.5 features?

  • implicitly typed local variables
    var myInt = 0;
  • automatic properties
    class Car
    {
       public string PetName { get; set; }
    }
  • extension methods
    static class MyExtensions
    {
      public static void DisplayDefiningAssembly(this object obj)
      {
      Console.WriteLine("{0} lives here:\n\t->{1}\n", obj.GetType().Name, Assembly.GetAssembly(obj.GetType()));
      }
    }
  • lambda expressions
    Increase lambdaDelegate = value => value * 2;
    Console.WriteLine(string.Format("Lambda expression: {0}", lambdaDelegate(5)));

I think you don't have to use all of them or even read all of them. Unfortunately I'm sure that a lot of developers can't even read many of them.

No comments:

Post a Comment