Archive for the 'C#' Category

The Stopwatch Class in .NET

Do you ever find yourself using DateTime to time a section of code?  Do you have code like the following?
DateTime start = DateTime.Now;

// Perform a long process
Thread.Sleep( 1968 );

DateTime end = DateTime.Now;
TimeSpan duration = end.Subtract( start );
Console.WriteLine( “This process took {0} ms”,
[...]

Writing An Appender For log4net

In log4net speak, an appender is an output destination for a log such as a file, the console, a database or even email.  log4net ships with so many appenders that most of us will never need to write our own.  There are cases where you may find a need for your own appender, for example, [...]

Easier Debugging with Attributes

Unless you have been inspecting some of the code generated by Visual Studio, you probably haven’t realized that there are several attributes that you can add to your code to make debugging easier. Some prevent you from stepping into sections of code, others change the way variables are displayed in the watch window.
The following [...]

Win32 COLORREF vs .NET Color

I have been migrating a large application from Win32/MFC to .NET and ran into an interesting problem. We store all of the application colors in the database as integers that represent the Win32 COLORREF value. COLORREF is just a DWORD representing the RGB value, so I thought that I could just take the value and get a .NET [...]

The Yield Statement in C#

Another often overlooked C# statement that was introduced in .NET 2.0 is yield. This keyword is used to return items from a loop within a method and retain the state of the method through multiple calls. That is a bit hard to wrap your head around, so as always, an example will help;
public static IEnumerable<int> [...]

Null Coalescing Operator

The first time I saw the ?? operator in C#, I did a double take and had to look it up. The operator, called the null coalescing operator was added in C# 2.0 and is pretty useful, but still fairly unknown.

Order order = GetOrder( id ) ?? new Order();
In the above code, if the return [...]

Nullable Types in C#

In .NET 1.0 and 1.1, if you wanted to store a null value for a value type (int, double, DateTime, etc) you would have to box it or write your own wrapper around it. The introduction of generics in .NET 2.0 allowed the concept of nullable types to be introduced into the language through the [...]

Introduction to XML Serialization

Many projects that I work on require me to serialize objects out to the file system and then retrieve them later. When I am serializing out program settings that are loaded in every time the program runs, I tend to use the Settings that come as a part of C# projects. If however the user [...]