Tip of the day: Using the null-coalescing operator over the conditional operator

I’ve recently been refactoring a lot of code that used the conditional operator and looked something like this: int someValue = myEntity.SomeNullableValue.HasValue ? myEntity.SomeNullableValue.Value : 0; That might seem less verbose than the traditional alternative, which looks like this: int someValue = 0; if (myEntity.SomeNullableValue.HasValue) someValue = myEntity.SomeNullableValue.Value; …or other variations on that theme. However, […]

Why should you be returning an IEnumerable

I’ve seen in many places where a method returns a List<T> (or IList<T>) when it appears that it may not actually really be required, or even desirable when all things are considered. A List is mutable, you can change the state of the List. You can add things to the List, you can remove things […]

I guess I've never needed to do this before…

I guess I’ve never created a struct in a while (at least in Visual Studio 2008 using C# 3.0) because I’ve just discovered that the Automatic Properties don’t work in structs. I’ve just created this struct: public struct CapacityUnit { public string Name { get; private set; } public long Multiplier { get; private set; […]

Monitoring change in XML data (LINQ to XML series – Part 5)

This is the 5th part in a series on LINQ to XML. In this instalment we will look at monitoring changes in XML data in the XML classes added to .NET 3.5. The XObject class (from which XElement and XAttribute, among others) contains two events that are of interest to anyone wanting to know about […]

Crazy Extension Method

Here is an example of a crazy extension method that alters the semantics of method calling. First the extension method: public static class MyExtensions { public static bool IsNullOrEmpty(this string target) { return string.IsNullOrEmpty(target); } } Instead of calling the static method IsNullOrEmpty() on string, we are turning it around to allow it to be […]