Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where/what is Error.ArgumentNull()?

Tags:

c#

.net

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.)

like image 698
Jon-Eric Avatar asked Mar 29 '13 22:03

Jon-Eric


2 Answers

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.

like image 177
Daniel A.A. Pelsmaeker Avatar answered Nov 13 '22 09:11

Daniel A.A. Pelsmaeker


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.

like image 5
Tim M. Avatar answered Nov 13 '22 09:11

Tim M.