.Net Tips – use [field:NonSerialized] to stop serializing your event handlers

In C#, when you define an event in your class, e.g.:

image

the event handlers will be serialized along with other properties, etc.

This is because under the hood, the compiler translates your event into the following, as can be seen through JetBrain’s dotPeek decompiler:

image

Since the generated EventHandler is not marked with the [NonSerialized] attribute there’s no way for the serializer to know that it should be ignored during the serialization process.

Solution 1 : implement event explicitly

One solution to this is to implement the event explicitly, so you end up with something along the line of:

image

Solution 2 : use [field:NonSerialized]

A much better solution would be to use the [NonSerialized] attribute on the event, and more specifically, you want to apply it to the private EventHandler instance that the compiler generates for you. Applying the [NonSerialized] attribute on the event generates a compiler error telling you that it’s only valid on field declarations:

image

image

So instead, if you prefix the attribute with the ‘field’ keyword everything will work as you’d expect:

image

Closing thoughts…

On a related note, you may have noticed that my event declaration assigns an empty handler to the event, this is to remove the need for null checking before invoking an event (which as you can imagine requires even more work to make thread-safe). There are other techniques (see @BlkRabbitCoder’s post on raising events safely and efficiently here for more details) to deal with this common problem.

In the case of a class that has to be serialized, this technique won’t work if the event handlers are not serialized as part of the object, because by the time it’s deserialized the event handler will be null.

So instead, courtesy of @BlkRabbitCoder, here’re two simple extension methods that encapsulates the code necessary to safely (prevents NullReferenceException) invoke event handlers in a thread-safe manner:

image

Further reading

Here are some more blog posts that go in to more detail about some intricacies with events in .Net:

Jon Skeet – Delegates and Events

Eric Lippert – Events and Races

Safely and Efficiently raising Events

F# – Adding custom indexer and slicer to your type

Indexer

If your have a type that represents a collection of values, adding a custom indexer gives you a natural way to index directly into the object using the .[ ] operator.

Take this simple Calendar class for instance, which keeps a map (F# equivalent of a Dictionary<TKey, TValue>) of notes against DateTime values:

image

By adding a custom indexer here I’m now able to write code like this:

image

Also, as you may have noticed already, F# allows you to use non-integer parameters in your indexer! In this case, I’m using a tuple of int * string * int. You can use this indexer from your C# code too:

image

One-Dimensional Slicer

That’s pretty cool, but we can go a step further by allowing you to use slicers on our types too. To allow users to get all the notes associated with a range of years, e.g. from 1999 to 2009, let’s add a slicer:

image

So now we can do this:

image

Two-Dimensional Slicer

Pretty awesome, right? But what if we want to refine our search criteria even more and let you specify a year range as well a range of months, e.g. get me all notes for April/May/June in the years 1999 to 2009. Thankfully, F# lets you define a two-dimensional slicer too:

image

This two-dimensional slicer allows me to query the calendar with a year range as well as a month range:

image

As you can see, indexers and slicers give the consumers of your code a much more intuitive way to interact with the data encapsulated in your type. Keep in mind though, that F# does not allow you to add slicer with more than two dimensions, but I think two-dimensional slicers should be good enough for most day-to-day requirements.

Update 2011/11/08:

Swapped out my verbose optional argument handling with defaultArg as Arseny Kapoulkine pointed out in the comments.

Find out which process is listening on a port

I needed to find out which process is listening on a port the other day and a quick search on SO showed me the way and all you need is to run:

netstat –aon | find /i "listening"

and you will get a list of the ports and the PID of the process listening on that port:

image 

Sweet!

.Net Tips – Getting the default value of a type outside of generics

To get the default value of a type, you’ve probably used the default keyword in .Net already:

   1: var defaultInt = default(int);        // 0

   2: var defaultObj = default(string);     // null

However, the use of the default keyword requires a type name to be specified at compile time, so you won’t be able to use it on a type which you discover at runtime. Instead, you will need to do something along the line of:

   1: public object GetDefaultValue(Type type)

   2: {

   3:     // Handle value types and reference types differently

   4:     if (type.IsValueType)

   5:     {

   6:         return Activator.CreateInstance(type);

   7:     }

   8:     else

   9:     {

  10:         return null;

  11:     }

  12: }

It’ll yield the same result as using the default keyword:

   1: var defaultInt = GetDefaultValue(typeof(int));        // 0

   2: var defaultObj = GetDefaultValue(typeof(string));     // null

.Net Tips – Finding GAC

By default the GAC folder in Windows is located at %windir%\assembly, you can find all the registered DLLs in that folder. Whilst you can open it in windows explorer and view it like any other folder, it is a somewhat special and allows you to have different versions of the same DLL registered in the GAC. 

Open up DOS prompt and navigate to the GAC folder, for instance:

image

and you can see that the GAC is actually a folder inside the assembly folder, and drilling a little deeper reveals that each DLL has its own folder which contains all the registered versions, each as a folder that contains the actual DLL inside:

image 

image

image

.Net 4

For .Net 4, the GAC location is now %windir%\Microsoft.Net\assembly.

Global Assembly Cache Tool

You can use gacutil.exe from the command line to view (e.g. gacutil /l), add (e.g. gacutil /i SomeAssembly.dll) or remove (e.g. gacutil /u SomeAssembly) the contents of the GAC, this of course, supports multiple versions of the same assembly too.