Vishful thinking…

Static constructors in generic types

Posted in .NET, C# by viswaug on August 22, 2007

Static constructors are a relatively little known feature .NET. It might probably be because they don’t have too many use cases where they fit in perfectly. But they did come in handy when I was looking for ways for make a list of all the properties in my class that were decorated in with a custom attribute. The static constructor was an ideal place to build the collection so that the collection can be exposed as a static property on my class.

But I did have my doubts on whether I will be able to use the static constructors effectively on generics types. Generics types are tricky when it comes to static constructors since the generic type can be customized with other type parameters. But turns out the static constructors do work effectively on generic types. The type parameters are available in the static constructor and the type parameter T in the static constructors for CustomType<int> and CustomType<string> refer to their corresponding type parameters even though they use the same CustomType<T> class.

The use of static constructors can be observed in the project attached to one of my previous blog post.


One Response

Subscribe to comments with RSS.

  1. Forrest said, on January 19, 2010 at 8:04 pm

    I’ve had many occasions to use static constructors. They can be a life saver.

    Sometimes you need to provide a stateful object, but ensure that only one copy exists. There’s a singleton pattern, but that really just mimics a static class. I find it more elegant in that sort of case, to just define a static class, and if it needs startup code, to put this in its constructor ( when that’s appropriate ).

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: