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
- Write a type that implements (at least nominally) the
IEnumerable
interface. - Give this type an
Add
method.
That’s it! For a quick example, see my answer to the Stack Overflow question.