Sometimes I see this in code samples:
throw Error.ArgumentNull("someParameter");
There's an example here, on line 89.
I'd like to use Error
in my own code. Where can I find it?
(I tried to find it on my own, I tried using
the namespaces at the top of that file, and I tried to get Visual Studio to locate it, so far no luck.)
It is a helper class defined by the creators of the library to make their lives easier.
Error.cs file:
internal static ArgumentNullException ArgumentNull(string parameterName, string messageFormat, params object[] messageArgs)
{
return new ArgumentNullException(parameterName, Error.Format(messageFormat, messageArgs));
}
If you are looking for similar functionality, take a look at Code Contracts (for non-Express editions of Visual Studio). Then you can write something like this:
using System.Diagnostics.Contracts;
void MyMethod(string someParameter)
{
Contract.Requires<ArgumentNullException>(someParameter != null);
// ...
}
...and it will throw an exception at run-time when this condition has not been met.
It is an internal helper class, with internal
visibility. That's why you haven't been able to locate it.
Microsoft source code uses this pattern in a variety of places.
But why do it? It enables you to throw a consistent, nicely-formatted, localized exception without having to put that logic in every exception handler.
Taking that a step further, some definitions even contain compiler directives, such as:
internal static ArgumentException InvalidEnumArgument( string parameterName, int invalidValue, Type enumClass ) {
#if NETFX_CORE
return new ArgumentException(Error.Format(CommonWebApiResources.InvalidEnumArgument, parameterName, invalidValue, enumClass.Name), parameterName);
#else
return new InvalidEnumArgumentException( parameterName, invalidValue, enumClass );
#endif
}
Other methods (such as PropertyNull()
) are decorated with code analysis suppression messages.
Again, it's simply a convenience/consistency mechanism to avoid repeating this code all over the place.
I probably wouldn't suggest trying to use this exact code in your own project, because your needs will be different. But you can certainly use it as a pattern.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With