Friday, May 31, 2013

Five C# Traps to Avoid

C# is an impressive and powerful programming language that serves both hobbyist and enterprise developers alike. But a tool as powerful as C# doesn't come without its sharp edges. Take a look five most common and most dangerous traps that developers will want to avoid when programming in C#.

 

  

C# 3.0 introduced the "var" keyword as a way to let the compiler infer the type of variable based on the expression used to initialize the variable. Don't fear the "var" keyword. It can save you time and typing.

Trap #2: Be careful with optional parameters

C# 4.0 introduces "optional" parameters. An optional parameter defines a default value to be used if the caller doesn't supply a value. In the past, the concept of default values for parameters was realized by overloading: When using optional parameters, the default "false" value was baked in to the calling assembly at compile time. Consumers of your utility library won't get the new default value unless they are recompiled. Be careful when creating public API's with optional parameters!

Trap #3: Deferred Execution in LINQ

LINQ makes querying of data so much easier than for/each loops with nested if blocks and other conditional logic. But remember that all of that fancy LINQ stuff is simply syntactic sugar over method calls. If you have cases where you want to ensure your LINQ queries are evaluated right away, convert them to a List via ToList(), or to an array via ToArray().

Trap #4: Overloading Methods in a base class

This is an interesting one that can trip you up if you're not aware of how .NET resolves overloads. The .NET runtime always favors the most-derived compile-time type. In this case, .NET will still call DoSomething(long). In general, you should avoid overloading methods defined in base classes.

Trap #5: Forgetting to unsubscribe from events

This has been around since the first version of C#, but still causes bugs from some people. the .NET runtime employs a very smart garbage collector to clean up objects in memory that are no longer used. It determines "used" by keeping track of what objects reference other objects. Once an object is found to not have any other objects referencing it, it's available for garbage collection and the memory can be released. Always make sure you unsubscribe from events you've subscribed to. It allows your unused objects to be collected sooner and puts less pressure on the garbage collector.

 

No comments:

Post a Comment