Home About

March 17th, 2009

10 C# Shorthands that improve productivity - 30

C# shortcuts and shorthand

One of the best things about C# is that as the language and libraries expand thought is put into keeping things readable. Below I have listed 10 shorthands that you can use to make your code tighter and less wordy. No doubt you know one or more already — but do you currently use all ten of them ?

1. The ? conditional evaluation operator

I first read about the ? operator in the “The C Programming Language” book by Brian Kernighan and Dennis Ritchie (first published in 1978, but I didn’t get around to reading it until well into the second edition). So this isn’t anything new. But it IS handy. It allows you to compress a common if-then-else pattern into a single assignment.

int x = 10;
int y = 20;
int max;

if (x > y)
  max = x;
else
  max = y;

Using the (Question) ? Positive Answer : Negative Answer patterns the above can be rewritten as:

int x = 10;
int y = 20;
int max = (x > y) ? x : y;

2. Null-Coalesce operator (??)

How often do you test for null values in your code? Often? Then the null-coalesce operator (??) comes in handy. To see how it works consider the following code example:

object cache = null;
object d = new object();
object e;

if (c != null)
    e = c;
else
   e = d;

It is obvious that we can rewrite this using the single ? operator :

object cache = null;
object d = new object();
object e = (c != null) ? c : d;

Using the ?? operator we can make it even shorter. If the left hand side is null, the right hand side is assigned.

object cache = null;
object d = new object();
object e = c ?? d;

3. Object Initializers

After you create a new object you often have to assign one or more of its properties. With the introduction of C# 3.0 it is now possible to use object initializers to both improve the readability of this, and to shorten your code.

Customer c = new Customer();
c.Name = "James";

c.Address = "204 Lime Street";

can be written as:

Customer c = new Customer { Name="James", Address = "204 Lime Street" };

4. The using statement

Often you will need to allocate a system resource such as a font, file handle, network resource etc. Each time you need such a resource there are three critical steps to go through: You acquire the resource, you use it, and then you dispose of it. If you forget to properly dispose of it you will have created a memory or resource leak. This is best illustrated through the following patterns:

     // 1. Allocation of the object
     Font font1 = new Font("Arial", 10.0f);
     try
     {
      // 2. The bit where we use the resource
     }
     finally
     {
     // 3. Disposal of the object
     if (font1 != null)
     ((IDisposable)font1).Dispose();
     }

The using statement allows us to compress this down to:

// Allocate the resource
using (Font font1 = new Font("Arial", 10.0f))
{
    // The bit where we use the resource
}
// Disposal is automatic

The using statement is intended to be used with objects that implement the “IDisposable” interface which in practice is all .NET objects that allocate and manage resources.

5. Aliases for long winded namespaces and types

The names of C# identifiers can become quite long. If you are doing Microsoft Office automation in C# you might want to do something simple like open MS Word and change a document. You can use the “using” statement to create an alias for either a class or a namespace.

using Word = Microsoft.Office.Interop.Word;
...
Word.Application = new Word.Application() { Visible = True; }

6. Nullable objects

A variable needs to have a value, it cannot be null. Sometimes it would be handy it was possible to assign “null” (eg. undefined) to a variable. .NET 2.0 introduced the Nullable generic that makes this possible. The following two lines produce exactly the same object:

Nullable<int> x = null; 
int? x = null;

By putting a ? following a variable definition the compiler will wrap a Nullable<T> generic around the type.

7. Automatic Properties

C# 3.0 introduced automatic properties. A property typically consists of (but doesn’t have to) a private variable which is exposed to the outside world through getters and setters. The following is common example of this:

public class Person 
{
 private string _firstName;
 public string FirstName 
 {
    get { return _firstName; }
    set { _firstName = value; }
 }
}

From C# 3.0 on we can reduce the above to:

public class Person
{
 public string Firstname { get; set; }
}

The C# compiler will automatically generate a backing variable and the correct get and set properties. Why is this useful? After all you could have just made a string variable in the class public instead.

By defining it as a property allows you to add the actual validation logic to your class at a later stage. The in-memory signature of the class won’t change which means that any external libraries compiled against your code will not have to be recompiled.

8. Type inference

In typical C# you will always carefully spell out your definitions:

    string MyString = “Hello World”;

From the right side of the declaration it is obvious that only one type (string) will ever match this definition. So instead of us doing the work, why not let the compiler figure this out?

    var MyString = “Hello World”;

The above definition will also create a string variable named “MyString”. It is important to note that C# is still strongly typed.There is no performance impact results from using type inference.

The compiler does all the work figuring out the data type at compile time. Of course this feature created two opposite camps, one that thinks var should be liberally applied, and another one that abhors the whole idea. The middle ground seems to be that var should be used there were its use is obvious.

var SeniorStaff = Employees.Where(s => s.Age > 35);         
foreach(var Member in SeniorStaff)
           Console.WriteLine("Name: {0} Age: {1}",Member.Name,Member.Age);

For example what type would SeniorStaff be ?

((System.Linq.Enumerable.Iterator<<>f__AnonymousType0>)(SeniorStaff))

This should make you glad that the compiler figured it all out for you. I wrote more about this in another post: Anonymous Types : The Basics.

9. Lambda Expressions

C# 2.0 introduced anonymous methods, which are methods defined inside a method. Incredibly powerful and a nice way to put all kinds of evaluation logic inside your code they had the drawback that they could be quite hard to read.

Func mySeniorStaffFilter = delegate(int a) { return a > 35; };

The above method takes an integer as a parameter, and returns a boolean. It checks if the staff member passed to it is older than 35. If so, it returns true.

Lamba expressions make things a little easier to read, while being functionally exactly the same:

Func mySeniorStaffFilter = a => a > 35;

Even better, you can define them anywhere a delegate would have fitted:

var SeniorStaff = Employees.Where(s => s.Age > 35);

10. string.IsNullOrEmpty

Not really a language feature, but a useful little library function in its own right. How often do you need to test if a string is empty? Or null? The string.IsNullOrEmpty method returns true if this is the case.

if (String.IsNullOrEmpty(s) == true)
    return "is null or empty";
else
     return String.Format("(\"{0}\") is not null or empty", s);

Optional and named parameters in C# 4.0

As a bonus a little on the upcoming C# 4.0 which will introduce optional and named parameters. It is quite difficult to see what all the hoopla is about until you realize what optional parameters will do to improve Office automation coding in C#:

Before optional and named parameters:

Word.Application app = new Word.Application() { Visible = true; }
object missing = System.Reflection.Missing.Value;
object filename = @"c:\Document.docx";
object readOnlyValue = true;

app.Document.Open(ref filename, ref missing, ref readOnlyValue, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing);

With the support of optional and named parameters this becomes:

Word.Application app = new Word.Application() { Visible = true; }
app.Documents.Open(@"c:\Document.docx",ReadOnly:true);

Microsoft Office certainly uses a lot of optional parameters. Note that in the first example all parameters are passed by reference. They still are in the second example. Behind the scenes the C# compiler creates the appropriate temporary variables to pass on, saving us from having to hand add them to the code.

To give proper credit, the above example comes from a video on this subject by Mike Ormond on Channel 9.

Image credit: Thinking About Something by Grazie Daverro

Be Sociable, Share!

Tags:

30 Responses to “10 C# Shorthands that improve productivity”

  1. andySF Says:

    very nice article, quite helpfully :)

  2. Niklas Says:

    why didn’t you use
    if (String.IsNullOrEmpty(s))
    instead of
    if (String.IsNullOrEmpty(s) == true)

  3. Gustavo Says:

    Very good tips/tricks Martijn’s…
    I’m using almost of them.

    Just one thing,
    if (String.IsNullOrEmpty(s) == true) [is the same of] if (String.IsNullOrEmpty(s))

    Best Regards

  4. Brian Says:

    The ?? operator is interesting (as I had never seen that before), but for the most part I actually prefer the wordy if/else versions (always with brackets too). I would expect every programmer to understand if/else immediately, but I could understand if someone didn’t immediately parse the operator equivalents, as it takes me just a little bit longer to parse them.

    For much the same reasons I’ve never taken advantage of type-inference, but I do like the foreach example you gave. I could see that as being an advantage. I never quite understood the advantage of writing var myString = “Hello” as opposed to String myString = “Hello”, but more than once I’ve wondered what specific type an enumerator was going to return – usually I just take a stab at it and let the compiler tell me if I’m wrong.

  5. taelor Says:

    Glad to see C# moving toward The Ruby Way. Its definitely got me interested in come .NET, espically working with MVC.

    The ternary operator works exactly the same as Ruby, except for the “;”…

    Now if C# would just let me say Object.send(“Method”) i’ll be a happy boy! (i know you can do this with reflection, but it takes like 4 extra lines of code.)

    Got any suggestions for a Ruby Fanatic who is coming over to the C# camp?

  6. Ivars Says:

    Brian, var keyword is usefull with constructs like
    StringBuilder builder = new StringBuilder();

    By using var you spare yourself one repetition of StringBuilder (or any other class name) without loosing clarity.
    var builder = new StringBuilder();

  7. Martijn Says:

    @Niklas and @Gustavo

    if (String.IsNullOrEmpty(s)==true)

    I made this example too verbose. I wanted to point out what it did, but it went against the purpose of the post ! Ooops.

    @Taelor

    That would require me to read up on Ruby I think ;-) I dabbled in Python before but have never gotten around to learning Ruby.

  8. Andre Loker Says:

    @taelor: the send functionality can be rebuilt in C# more or less using extension methods. I threw something together for you, have a look at http://blog.andreloker.de/post/2009/03/18/Rubys-send-in-CSharp.aspx

  9. taelor Says:

    @Martjin

    aloker just wrote a blog post about the .send method. I haven’t gotten to play around with it yet, but looks very promising!

    http://blog.andreloker.de/post/2009/03/18/Rubys-send-in-CSharp.aspx

  10. Chris Says:

    One note about String.IsNullOrEmpty I find it completely useless. The problem is the way I check my string is
    if (a == null || a.Trim() == “”) …

    and of course
    if (string.IsNullOrEmpty(a.Trim()))…
    will throw an exception if null.

  11. Amgad Says:

    Nice post. More C# shorthands to make us type less code, what else would a programmer need :)

  12. AllenDang Says:

    nice article! very usefull.

  13. Dave Says:

    “By using var you spare yourself one repetition of StringBuilder”

    Visual Studio Intellisense will automatically suggest the type after you type “new”, so you’re saving yourself one Tab.

  14. robert mcbean Says:

    i would write

    object e = c ?? d;

    as

    object e = c ?? new object();

  15. Whakate Says:

    This is extremely helpful. There are indeed a few I did not use. Thanks

  16. Charles Strahan Says:

    Excellent post! I forgot about that null-coalesce operator – could come in handy :) .

    BTW, I like the way you have your code formatted – it’s something that I’m having a ridiculously hard time getting to work in WordPress. Perhaps you’d have a suggestion? I have the “SyntaxHighlighter Evolved” plugin working just fine, but my problem is that switching to the Visual Editor removes all of the padding to the code. If you could let me know how you add c# snippets to your blog, I’d love you for ever :D .

    Kind regards,
    -Charles

  17. The Cave » Blog Archive » C# Shorthand Says:

    [...] C# conveniences to make coding easier: [...]

  18. Martijn Says:

    Hi Charles,

    I have disabled the Visual Editor — its a pain. When I have a post that contains much code I write it in an HTML editor and cut & paste it into WordPress.

    Not the easiest solution, but it keeps things in the right spot. What I really would like to have is a full-screen code editor in WordPress similar to the visual editor.

    Martijn

  19. Marf Says:

    Great tips, a few in here that even I didn’t know. However I was reading your one tutorial on anonymous types and you mention using LINQ rather than lambda. I prefer using LINQ statements as they are more human readable “from S in Employees where S.Age > 35 select S” versus “Where( s => s.Age > 35)”. Any reason you chose to put Lambda in there rather than LINQ?

  20. Visual C# Kicks Says:

    My favorite is the get-set shorthand.

    I’m also wearing of using var. It definitely helps to avoid repeating yourself but indicating variable types is not always repetitive. Sometimes it is part of code clarity. Developers just have to use it properly and many don’t

  21. James Tiet Says:

    This is really nice article, I love it

  22. juharr Says:

    Wow, I use all of these except for #5, just never found the need. And for #10 not only do I use that, I also wrote a little extention method (those should be on the list) to make it work the way I want it to

    public bool IsNullOrEmpty(this string s) { return string.IsNullOrEmpty(s); }

    This way I can have

    if(myString.IsNullOrEmpty())

    instead of

    if(string.IsNullOrEmpty(myString))

    which I think is more readable and more natural with intellisense.

  23. Nick Olsen Says:

    Good info. Didn’t know about the ?? operator.

    Always looking for ways to reduce the number of characters I have to type!

  24. Rocky Madden Says:

    Nice write up. I love short hand approaches to make every line of code count. I was unaware of the LINQ statements, thanks!

  25. Charles Boyung Says:

    #8 is a horrible thing to do. That item is a case of pure laziness and leads to less readable code in the long run. Usability is something you can strive for IN your code as well, not just with the resulting interface. And as the name of the usability book suggests – “Don’t Make Me Think”. Why make the compiler and future maintainers of your code try to figure things like this out when you can very easily just define the type right then and there? Only valid reason is that you are too lazy to do it the right way.

  26. Coder Says:

    Hey thanks for posting this, although I now prefer C++.

  27. josh Says:

    Why do

    int max = (x > y) ? x : y;

    instead of

    int max = Math.max(x, y):

    ?

  28. Rarius Says:

    Speaking as a software engineer of over 20 years experience, I hate coding shorthands. Time and again, I have found that they make code less readable and while they may make the initial coding faster (slightly), they have a much larger (detrimental) impact on code maintainability. Code should be written on the assumption that some poor programmer (usually you!) will need to read and understand the code sometime in the future, usually after all knowledge of the code has been forgotten.

    IMHO the conditional evaluation and null-coalesce operators should never have been allowed in C#. The longhand for both of these operators is much clearer and takes only a few seconds to type.

    While I think many of the other things described above are very useful and laudable (“using” for example) several of them as pure lazyness laying the code open to misinterpretation. This in turn impacts maintainability.

  29. Moutasem Alawa Says:

    Thanks for sharing, the one thing i am stunned about is Null-Coalesce operator is totally new for me.

  30. Prasetiawan Says:

    I love the programming and am very happy to visit your website. I will make your website one of my reference website to learn programming. thank you very much for this article helpful articles. Regards,
    C Programming Blog


Most popular

    Sorry. No data so far.

Recent Comments
  • Juan Romero: Hi there, it’s a neat little class, but I believe you could do the same thing with the WebClient...
  • anthosh: Hey, THank you very much for your tutorial. It was awesome. But i have a problem that i am not able to...
  • bian: how to get passphase if i have encrypt and decrypt string?? Thanks alot
  • Michael: Hi, I really like your post, thanks a lot, it really helped clear up a few things I could not remember how...
  • Bharat Prajapati: i was trying to import keyword dictionary to this plugin which is in csv format, but i get an error...