A perfect blend of all things Dot Net
Until recently I thought this was a well-known feature. After demonstrating it a few times, I found out it wasn’t.
A long time ago, in an cubicle far, far away, someone created the .Net Framework. To cut a long story short, they simultaneously produced guidelines for creating Exception classes, which you should always use or face having your fingernails pulled out with a staple-gun.
The guidelines state:
“Use the common constructors shown in the following code example when creating exception classes. “
[C#]
public class XxxException : ApplicationException
{
public XxxException() {… }
public XxxException(string message) {… }
public XxxException(string message, Exception inner) {… }
public XxxException(SerializationInfo info, StreamingContext context) {…}
}
If you don’t believe me, you can look here:
Now, I don’t know about you, but I can’t remember all that every time I create a custom exception class. Maybe that’s why the guidelines also state:
In most cases, use the predefined exception types. Only define new exception types for programmatic scenarios, where you expect users of your class library to catch exceptions of this new type and perform a programmatic action based on the exception type itself.
But let’s ignore that. It’s not relevant.
So, did you know that there is a Visual Studio code snippet that does the work for you? Here’s how you use it.
Exception
You then get the following code, free of charge:
[global::System.Serializable] public class MyException : Exception { public MyException() { } public MyException(string message) : base(message) { } public MyException(string message, Exception inner) : base(message, inner) { } protected MyException( System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) : base(info, context) { } }
What’s more, you get code snippet functionality which automatically changes the names of all the constructors when you change the name of the class.
I wonder what other code snippets are available. Do you know of any cool ones? What are your favorites?
Thomas Claudius Huber
February 16th, 2008 at 12:00 am
Hi Richard,
my favorites are propa and propdp. In a C#-Project created with Visual Studio 2008 these new snippets create the functionality for attached and dependency properties.
Thomas
Frank Quednau
February 18th, 2008 at 10:43 am
My code doesn’t throw exceptions, hence I don’t write any