Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Code snippet: Auto complete for ArgumentNullException in Visual Studio

I'm often writing a c# code that goes like this:

    void func(object myObject)
    {
        if (myObject == null)
        {
            throw new ArgumentNullException("myObject");
        }
        ...

How do I write an auto-complete in Visual Studio 2012 for that type of code, so that I don't have to keep typing this all the time?

like image 517
galets Avatar asked Sep 17 '25 17:09

galets


2 Answers

Since there hasn't been an interest, I'm going to close on this question by posting my own solution. Putting following file into C:\Program Files (x86)\Microsoft Visual Studio 11.0\VC#\Snippets\1033\Visual C#\ifn.snippet will do the trick:

<?xml version="1.0" encoding="utf-8" ?>
<CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
  <CodeSnippet Format="1.0.0">
    <Header>
        <Title>ifn</Title>
        <Shortcut>ifn</Shortcut>
        <Description>Code snippet for if (arg==null)</Description>
        <Author>sam green</Author>
        <SnippetTypes>
            <SnippetType>Expansion</SnippetType>
            <SnippetType>SurroundsWith</SnippetType>
        </SnippetTypes>
    </Header>
    <Snippet>
        <Declarations>
            <Literal>
                <ID>argument</ID>
                <Default>arg</Default>
                <ToolTip>Argument</ToolTip>
            </Literal>
        </Declarations>
        <Code Language="csharp"><![CDATA[if ($argument$ == null)
        {
                    throw new ArgumentException("$argument$");
        }$end$]]>
        </Code>
    </Snippet>
  </CodeSnippet>
</CodeSnippets>
like image 146
galets Avatar answered Sep 19 '25 07:09

galets


I defined a ReSharper shortcut for this using the keywords "argnull" that auto-generates and guesses the parameter I want. It's about the same effect as your solution, I think, though you don't need to muck with XML or where to place files.

Here's an example of a ReSharper VB.NET approach:

if $VAR$ is nothing then
  throw new ArgumentNullException("$VAR$")
end if
like image 21
Matt Eland Avatar answered Sep 19 '25 07:09

Matt Eland