What I Like About C#

Coming from the Open Source world I had never really worked with .NET – except for some minor Sharepoint 2007 stuff – until last September. That’s when I joined a project maintaining a .NET application written in C#.

Since I had previously worked with Java, becoming a (visiting) C# developer wasn’t that much of a leap. After all, C# was partly influenced by Java (learning new frameworks did of course impose some learning curve, but that’s of course independent of language).

C# has some nifty features that Java lacks, though. In many ways, it feels like a more modern language — pardon me for saying so! :D

What follows are some of the things that I’ve started to like about C#.

Implicit variable declaration

Having to declare the type of every single variable can sometimes be quite annoying (Java). In C# (3.0), you can both explicitly declare the type of the variable, or use implicit variable declaration using the `var’ keyword:

var car = new Car();

This is not only quicker to type – at least under some circumstances, but can also come in very handy when getting your objects from factories or repositories, services or whatever. Your IDE, i.e. Visual Studio, will of course assist you (afterwards) if necessary as the variable is still strongly typed.

yield return

One of the things you can do in C#, but not in Java, is to yield the return value from a function. Here’s an example:

public class CarDealer {

    public List<Car> availableCars;

    public IEnumerable<RegNumber> GetAllAvailableCarRegNumbers() {
        foreach( var car in availableCars ) {
            yield return car.RegNumber;
        }
    }

}

Compare this to manually collecting the RegNumbers in Java:

public List<RegNumber> getAllAvailableCarRegNumbers() {
    List<RegNumber> regNumbers = new ArrayList<RegNumber>();
    for( Car car : availableCars ) {
        regNumbers.add( car.getRegNumber() );
    }
    return regNumbers;
}

A colleague of mine has written more about yield and yield break.

Object Initialization

In C# you can initialize new objects on the fly:

var car = new Car { Brand = "Bentley" ...  };

Somewhat similar to using Java’s Double Brace Initialization albeit a bit cleaner.

Anonymous functions

C# supports anonymous functions and lambda expressions. Here are some silly examples:

public void DoSomething() {

    UseAnonymousFunction(() => 1 + 1); // prints 2
    UseAnonymousFunction(() => 2 * 2); // prints 4

    var a = 0;
    UseAnonymousFunction(() =>
                                {
                                    a += 20;
                                    return --a;
                                }); // prints 19
}

private void UseAnonymousFunction(Func<int> func)
{
    Console.WriteLine(func.Invoke());
}

You can also pass these functions around:

var a = 10;
var myFunction = new Func<int>(
    () => a--
);

UseAnonymousFunction( myFunction ); // 10
UseAnonymousFunction( myFunction ); // 9

Apparently, anonymous functions are schedueled for JDK 7.
Sigh; even PHP has anonymous functions (since v5.3.0).

Linq

If I were supposed to continue working with C#, I’d definitively make sure to master Linq.

What follows is a basic example of how to sort a list of objects using Linq in C#.

public class Car {
    public List<Part> Parts { get; set; }
}

public class Part {
    public string Name { get; set; }
    public DateTime? availableFrom { get; set; }
}

// somewhere else in the code
var lastPartAsSortedAlphabeticallyByName = car.Parts.OrderBy(part => part.Name).Last();

// or perhaps
var firstPartAsSortedChronologically = car.Parts.OrderBy(part => part.availableFrom).FirstOrDefault();

Beats writing comparator logic, lots of if/else, etc…

Linq can also be a very powerful tool for searching for and selecting specific items from collections.

// single item
var myPart = car.Parts.Where( part => part.Name.Equals("MyPart") ).First();

// multiple items
IEnumerable<Part> myParts = Parts.Where( part => part.Name.StartsWith("MyPart") );

Of course, this is only the simplest of examples. You can also do a lot of other, more complicated stuff with Linq — making a lot of your code superfluous and ready for the delete button :)

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

  • @twitter

  • Tags

  • Topics

  • Recent Comments

  • Topic Map Feeds