Currently Browsing: .NET Examples

Lazy evaluation of variables in C#

In an attempt to revitalize this blog, I’m going to write a few post on random bits of code that I’ve found useful recently. The first sample is Lazy<T>. This simple class allows you to delay the initialization of a variable till its first use. This can come in handy if you have a method with many code paths and you’d like to initialize all variables at the start of the method without the overhead of initializing unnecessarily. Here’s a usage example: var fileCount = new Lazy<int>(() => Directory.GetFiles(".").Length); And the class: public...
read more

How to use Debug.Write and Trace.Write across app domain boundaries

If you’ve ever written an application that uses multiple application domains you may have noticed that calls to Debug.Write or Trace.Write in new application domains get lost, especially if you’ve add the TraceListener in code (e.g. “Debug.Listeners.Add(new ConsoleTraceListener());”). Fortunately this is reasonably easy to solve with just two classes, one to handle the Debug.Write events in the child domain and another to handle the communication of messages between domains. I’m going to use a TraceListener implementation that I originally wrote to help with the writing of...
read more

Lazy initialization in VB.NET

Lazy intialization is a method used to set the values of objects at the latest possible moment (if at all.) The idea behind it is that it’s often hard to tell if and when an expensive operation needs to execute, so putting off until the result’s actually needed is going to save processing time. While it’s possible to implement lazy intialization in many languages, VB.NET provides a keyword that makes thread safe lazy intialization easy, and that’s the the Static keyword (this is different from Shared, or C#’s static.) The Static keyword can be used in place of Dim when...
read more

When failure is not an option

At one point in time or another, any developer will come across code that isn’t stable, either it’s some poorly supported third party component, or maybe one of your internal developers is a bit of a wild child. In either case, you’re going to need to pave the way for stability, and I’m here to help. The first key to stability is the obvious try..catch exception handling block, and given you catch a specific enough exception then your code can continue on its way. A bigger issue arises when the code your calling is multi-threaded. While being great for performance, they can be a...
read more

Next Entries »