Reputation: 17275
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.)
Upvotes: 8
Views: 2104
Reputation: 50326
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.
Upvotes: 8
Reputation: 3428
That is a custom internal type, it does not exist in the BCL.
namespace System.Web.Http
{
/// <summary>
/// Utility class for creating and unwrapping <see cref="Exception"/> instances.
/// </summary>
internal static class Error
{}
}
You can copy it from there and you it if you want.
Upvotes: 0
Reputation: 54377
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.
Upvotes: 5