Yet another quick primer on custom initializers in C#

A user on Stack Overflow recently asked if he could write initialization code like this:

Frame<int, int>[] test = new Frame<int, int>[3] {{2,5},{3,6},{4,7}};

The first few answers that trickled in effectively said that no, you can’t do this, since the user’s custom Field<T1, T2> type did not have its own initializer. One user even made this claim (the answer was deleted after Eric Lippert pointed out its falsehood):

The only type (that I know of) that allows pair initialization as in your sample code is Dictionary<>.

Thanks goodness this isn’t true! It is possible to use custom initializers for your own types in C#. (Wouldn’t it have been kind of silly for C# to special case the Dictionary<TKey, TValue> class? I mean, honestly?)

I’m sure plenty of other blogs have introduced the world to custom initializers in C# already; but here’s the thing. I’m shooting for a post a day in 2011 on this blog (by the way, if you’re reading this, how about nominating me for the 2011 Bloggies? I realize there’s no possible way I could win or even be a runner-up; but I figure promoting this blog in any way possible can’t hurt!), and today my wife and I are flying from Philadelphia—where we’ve been visiting family for the holidays—back to San Francisco—where we live—so I won’t really have much time to post this evening. And so I had to write a post now. But I couldn’t think of anything. So my wife suggested just looking at a question I recently answered on Stack Overflow and writing a post about that. So that’s what I’m doing. Get off my back already!

OK, so this is going to be the quickest primer on custom initializers in C# ever. Are you ready?

Here it is: the quickest primer on custom initializers in C# ever

  1. Write a type that implements (at least nominally) the IEnumerable interface.
  2. Give this type an Add method.

That’s it! For a quick example, see my answer to the Stack Overflow question.

About these ads

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: