It’s late. I’m hacking in the VS extension COM jungle. Cut me some slack.
Tag: C#
Cleaner Event Declarations in C#
The traditional event declaration in C# looks something like this:
public event EventHandler Executed; protected virtual void OnExecuted() { if (this.Executed != null) this.Executed(this, EventArgs.Empty); }
The gratuitous null check in the virtual OnXYZ event caller has always pestered me and I just learned an interesting alternate syntax to avoid this boiler plate code! Behold the cleaner alternative:
public event EventHandler Executed = (o, e) => { }; protected virtual void OnExecuted() { this.Executed(this, EventArgs.Empty); }
When declaring the event start by assigning it to a lambda, then your event will never be null. Of course there is a minor performance impact to this, but we’re not prematurely optimizing right? Riiiiight?
ints by reference in C#
I wasn’t sure about this but I find this interesting:
object x = 7; object y = 7; Console.WriteLine(object.ReferenceEquals(x, x)); Console.WriteLine(object.ReferenceEquals(x, y));
Which prints:
True False
Of course this is because we’re assigning the ints to objects, so they become boxed. This could be very useful to me…
[EDIT]
This actually works well except for the case of strings. They are already reference types and apparently they are special cased in .net such that there is always only a single instance of a partictular string.
RE: Delusions of Programming
I read a post by Jonathan Edwards recently called Delusions of Programming. Where he makes a few interesting points about the importance of IDE support. As someone who is a big fan of Boo I can definitely attest to the truth of his words. In my own words I have come to a similar lesson: good tooling can make even a bad language powerful and vice versa. As much as I love Boo and as powerful as it is, I’m still far more productive in C#. If Boo had the same quality of IDE tooling, and error messages it would blow C# out of the water… but it doesn’t. The actual language itself is probably less than 50% of the whole story.
Very Handy Addition to Linq
I have found this custom extension method to be extremely useful when working with linq:
public static IEnumerable<T> Cast<T>(this object value) { var enumerableOfTValue = value as IEnumerable<T>; if (enumerableOfTValue != null) return enumerableOfTValue; var enumerableValue = value as IEnumerable; if (enumerableValue != null) return Enumerable.Cast<T>(enumerableValue); return Enumerable.Cast<T>(new[] { value }); }
Basically it lets you turn any object into an IEnumerable<T>. Its especially handy when working with an object and you don’t know if it’s a single object or a set.
You must be logged in to post a comment.