Skip to content

Instantly share code, notes, and snippets.

@litera
Last active August 29, 2015 14:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save litera/e20d894536f631aecf7b to your computer and use it in GitHub Desktop.
Save litera/e20d894536f631aecf7b to your computer and use it in GitHub Desktop.
Method parameter checking Visual Studio code snippets

Parameter checking using Code snippets

Don't write the same code over and over again and rather save these two code snippets to simplify your coding. YOu will still have the same code in your methods, but will gain two main things:

  1. You will be faster doing this as code snippet template will do majority of typing for you
  2. You won't misspell parameter name when providing its testual name to exception constructor

So until we get Visual Studio 2014 with new C# ?. operator this is the simplest way without additional code in the form of either extension methods or other things.

There are two snippets

ONe is for null parameter checking and the other for strings that they're not null or whitespace.

<?xml version="1.0" encoding="utf-8"?>
<CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
<CodeSnippet Format="1.0.0">
<Header>
<Title>Parameter check for objects (not string type)</Title>
<Author>Robert Koritnik</Author>
<Description>Template that adds a parameter check code block.</Description>
<Shortcut>checknull</Shortcut>
</Header>
<Snippet>
<Declarations>
<Literal>
<ID>param</ID>
<ToolTip>Replace with parameter name.</ToolTip>
<Default>value</Default>
</Literal>
</Declarations>
<Code Language="CSharp">
<![CDATA[if ($param$ == null) {
throw new ArgumentNullException("$param$");
}
$end$]]>
</Code>
</Snippet>
</CodeSnippet>
</CodeSnippets>
<?xml version="1.0" encoding="utf-8"?>
<CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
<CodeSnippet Format="1.0.0">
<Header>
<Title>Parameter check for strings</Title>
<Author>Robert Koritnik</Author>
<Description>Template that adds a parameter check code block for strings.</Description>
<Shortcut>checkstring</Shortcut>
</Header>
<Snippet>
<Declarations>
<Literal>
<ID>param</ID>
<ToolTip>Replace with parameter name.</ToolTip>
<Default>value</Default>
</Literal>
</Declarations>
<Code Language="CSharp">
<![CDATA[if (string.IsNullOrWhiteSpace($param$)) {
throw new ArgumentException("String '$param$' should not be null, empty or whitespace only.", "$param$");
}
$end$]]>
</Code>
</Snippet>
</CodeSnippet>
</CodeSnippets>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment