Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Argument Helper

0.00/5 (No votes)
20 Mar 2009 1  
An argument helper for checking arguments passed into methods.

Introduction

This code example shows how to make your public methods safer to use. Especially, if they are to be used as libraries by others who don't have access to the source code.

Background

I thought I would share some functionality to help argument checking for public methods/properties. All public/internal methods in assemblies should have appropriate argument checking and throw the appropriate exceptions:

  • ArgumentNullException – A null was passed when an argument must be specified.
  • ArgumentException – An argument passed was invalid for a certain reason.

Using the code

Obviously, the exceptions should only be thrown where appropriate, but if the code within your method requires the arguments to be in a certain state, you need to ensure it. To this end, I have added some helpers:

ArgumentHelper.AssertEnumMember<T>(enumArgument);
ArgumentHelper.AssertEnumMember<T>(enumArgument, enumValuesValid[]);
ArgumentHelper.AssertNotNull<T>(notNullArgument, " notNullArgument ");
ArgumentHelper.AssertNotEmptyAndNotNull(notEmptyAndNotNullArgument, 
               "notEmptyAndNotNullArgument");

They are pretty self explanatory, but are useful for throwing for simpler checking.

/// <summary>
/// Retrieves all available plugins based on plugin type.
/// </summary>
/// <param name="pluginType">Type of plugins to get.</param>
/// <param name="plugins">List to populate.</param>
/// <param name="pluginFile">Some plugin file.</param>
/// <param name="canBeNull">Can be null string.</param>
/// <returns>True if successful.</returns>
public static bool GetAllPlugins(PluginType pluginType, IList<string> plugins, 
                                 string pluginFile, string canBeNull)
{
    ArgumentHelper.AssertEnumMember<PluginType>(pluginType, 
                   new PluginType[] {PluginType.Global, PluginType.Packager}); 
    ArgumentHelper.AssertNotNull<IList<string>>(plugins, "plugins");
    ArgumentHelper.AssertNotEmptyAndNotNull(pluginFile, "pluginFile"); 

    if (canBeNull == null) //can be null so need need to check above.
      return false;
}

History

  • 20/3/2009 - Uploaded.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here