Visual Studio Project/Item Template Parameter Logic

maschall picture maschall · Jul 15, 2011 · Viewed 13.6k times · Source

Since I have only seen a few posts on the topic but no in-depth explanation of the logic for parameters in templates for Visual Studio, I figured I'd post this here.

Following the MSDN article you can add custom parameters to your template that can be altered with a Wizard if you want to alter them.

In any file of the template (other than the template file itself) you can add logic based on the parameters. There are only three keywords to be used with the logic. $if$ ( %expression% ), $else$, and $endif$. So say I have the following in a template file:

public string foo( string a )
{
    return string.Format( @"foo( {0} );", a );
}

And we want to add some logic for whether or not we want to check if "a" is null or empty

public string foo( string a )
{
$if$ ( $shouldCheckForNullOrEmpty$ == true )
    if ( !string.IsNullOrEmpty( a ) )
$endif$

    return string.Format( @"foo( {0} );", a );
}

Of course you may want to add the braces for the if statement so you may need more than one logic block.

So that is not too bad, but there are a few tricks to this. The $if$ check for string match, that is shouldCheckForNullOrEmpty must equal "true". It was also tempted in writing $if$ ($shouldCheckForNullOrEmpty$ == "true"), but that will not work.

Single if statements with single expressions are pretty simple so now for a bit more complex example:

public string foo( string a )
{
$if$ ( $parameterCheckMode$ == ifNullOrEmpty )
    if ( !string.IsNullOrEmpty( a ) )
$else$ $if$ ( $parameterCheckMode$ == throwIfNullOrEmpty )
    if ( string.IsNullOrEmpty( a ) )
        throw new ArgumentException();
$endif$ $endif$

    return string.Format( @"foo( {0} );", a );
}

As you may be able to tell, this is a switch statement for the parameter mode. You may note that there is no $elseif$ so you have to make it $else$ $if$ but will have to add an extra $endif$ at the end.

Lastly, I have yet to find and or or symbols for the logic. I got around this by just using the logic equivalence:

and -> $if$ ( expression1 ) $if$ ( expression2 ) $endif $endif$

or -> $if$ ( expression1 ) statement $else$ $if$ statement $endif$ $endif$

Hopefully this helps someone.

Answer

Harry S picture Harry S · Apr 10, 2018

For the logic and and or
and is:
&&
while or is:
||

So, an if statement with and in it would look like this:

if ((a != null)&&(a !=""))
{
    Console.Write(a);
}

And an if statement with or in it would look like this:

if ((b != null)||(b >= 5))
{
    Console.Write(b);
}

For the template, you could Export a *.cs file as a template. It is under Project>Export Template...

(I was using VisualStudios 2017)

Hopes this helps.