Microsoft released a number of significant changes and additions to Visual Studio and the .NET Framework over the last year or so. So you’re not alone if you find yourself occasionally feeling overwhelmed by all of the new changes. But if you think current projects keep you too busy to look at the latest releases, you need to remember the old adage about taking time out to sharpen your saw. In this article I’ll take some time to show you some great new additions to C# that can sharpen your productivity without a lot of effort.
Additions to C# in.NET Framework 3.5
In my first article about Visual Studio productivity enhancements, Microsoft Visual Studio 2008 Improvements, in the March 6, 2008 WindowsDevPro Update, I looked at improvements that developers can easily use without forcing us to change existing solutions or adopt entirely new coding paradigms. The same thing goes with the Visual Studio 2008/.NET Framework 3.5 Visual C# features that I’ll discuss here. All of these features are made possible through additional compiler support in the form of new syntax. This means that these new changes take only a few minutes to learn, yet they have the potential to provide significant productivity benefits.
The Coalescing Operator
It could be argued that the coalescing operator represents a minor change to C# in .NET Framework 3.5 and that if you’re not playing around with SQL Server LINQ, you might even miss this handy new bit of functionality. But if you’re too busy to check out LINQ, you still need to check out the coalescing operator as it can have a huge impact on your coding efficiency. Take a look at this code sample:
string middleName = txtMiddleName.Text ?? "";
Customer cust = GetCustomer(id) ?? new Customer();
I love it because it’s like having T-SQL’s ISNULL() or COALESCE() functions in C#, except that they’re implemented as an operator in C# which makes it lean, mean, and easy to use just about anywhere. I’ve found that using this operator can help to ensure that code remains sufficiently robust (by ensuring default values where needed) with a modicum of effort.
Object and Collection Initializers
I’m in love with C#’s new initializers; they’re valuable in many contexts because they’re an exceptionally clean way to create new objects or collections. For example, in applications where a business object is being edited or created based on an ID, if the ID is 0, then the action can represent the creation of a new object; otherwise it represents the ID of the object to edit. With object initializers I can easily define that logic in my code in a single line without jeopardizing readability:
User u = uId == 0 ? new User { Id = 0 } : GetUser(uId);
u.FirstName = txtFirstName.Text;
// etc.
I also find collection initializers to be extremely useful for simple logical evaluations like the following:
List<string> northWestStates =
new List<string> { "Montana", "Idaho", "Washington", "Oregon" };
if(northWestStates.Contains(currentState))
// state is a NW state
Of course, hard coding your logic like this doesn’t always make sense. But in cases where one-off evaluations are required by business logic, you can’t beat initializers for their ability to let you quickly code up a viable solution with minimal clutter.
Auto-Implemented Properties
I’ve also been using auto-implemented properties for a few months now. Each time I use this new syntax to create properties I’m amazed at how easy properties are to create now.
// 'traditional properties
private string _name;
public string Name
{
get { return _name; }
set { _name = value; }
}
// Auto-Implemented
// exact same functionality, but less code
public string Name { get; set; }
Ironically, the hardest thing to get used to with automatic properties is remembering to use code snippets to create them, because that makes them a lot faster to implement. I frequently find myself creating properties by hand because it’s so easy with this new syntax.
Extension Methods
The thing I love most about C# in NET Framework 3.5 is extension methods. They’re important in making LINQ work, but I find that they’re extremely valuable in just about everything I do now. They’re extremely elegant and have virtually no learning curve, making them the perfect addition to any C# developer’s arsenal. Best of all, they help overcome some of the repetitive logic problems that I’ve been dealing with for so long–without making me link out to helper classes and other hacks.
Here are two extension methods that I’ve become addicted to:
public static bool IsEmpty(this string input)
{
return string.IsNullOrEmpty(input);
}
public static string TrimTo(this string input, int len)
{
if (input.IsEmpty())
return input;
if (input.Length > len)
return input.Substring(0, len);
return input;
}
IsEmpty() may not look like much (it looks like the old Visual Basic function IsEmpty()), but it’s become a life-saver for me. This is because checking strings in C# to see whether they’re null or empty gets a bit tedious. I know the string class offers a static .IsNullOrEmpty() method, which is much better than manually making those checks yourself, but it still ends up looking bulky in code. With IsEmpty() I’m able to abstract that same logic into a much cleaner bit of syntax that improves readability:
// good
if(text == null || text.Length < 1)
// string is empty// better
if(string.IsNullOrEmpty(text))
// string is empty// best (for me)
if (text.IsEmpty())
// string is empty
The .TrimTo() method does more than just please my sense of aesthetics. In fact, it saves me oodles of time. For example, when persisting business objects to a database there’s that annoying impedance mismatch between SQL Server (or any other database) and .NET: Where strings in .NET are of virtually any length, and strings in databases are typically constrained in size (to say, something like varchar(20)). Things get even worse with data such as Middle Names – which can be empty/null or up to a certain allowed length. Accordingly, a lot of my code accounts for that mismatch (whether I’m using stored procedures or LINQ) and looks like this:
Customer customer = new Customer();
if (string.IsNullOrEmpty(txtMName.Text))
customer.MiddleName = "";
else
{
if (txtMName.Text.Length > 30)
customer.MiddleName = txtMName.Text.Substring(0, 30);
else
customer.MiddleName = txtMName.Text;
}
With .TrimTo() and the coalescing operator I’m able to ditch more than seven lines of code for the following single line of code that does the same thing:
customer.MiddleName = txtMName.Text.TrimTo(30) ?? "";
In each of my projects I’m now creating a static class or two to house my extension methods, which I create on a project-by-project basis to address common logical problems and repetitive tasks. And by placing these static classes into my projects without an explicit namespace, I’m able to access my encapsulated solutions wherever they’re needed, which has been a great productivity boost.
All This and a New Compiler Too
C# in .NET Framework 3.5 offers many great new additions; I’ve just scratched the surface here. You can use all of the additions that I’ve mentioned with very little effort or additional learning. And best of all, since these benefits are provided thanks to new compiler functionality, you can easily upgrade existing .NET Framework 3.0 and .NET Framework 2.0 applications to .NET Framework 3.5 without the pain associated with .NET Framework 1.0 to .NET Framework 2.0 conversions.
more on: http://www.windowsdevpro.com