Take the 2-minute tour ×

I'm trying to write a vs code snippet that will take the selected and surround it with an if null check, i.e.

accgrp.CREATEDATE = DateTime.Now;

will become:

if (accgrp.CREATEDATE == null)
            accgrp.CREATEDATE = DateTime.Now;

I've got as far as the below. $selected$ only seems to work the last time it is used, if used more than once, the other instances where you would expected to see the selected code are blank. I understand the code below wouldn't do exactly what I want, as I wont get the right hand side of the assignment, btu it would be good enough.

				<ToolTip>Expression to evaluate</ToolTip>
		<Code Language="csharp"><![CDATA[if ($selected$ == null)
	$selected$ = $expression$$end$	 

Can anyone help?

share|improve this question

2 Answers 2

up vote 1 down vote accepted

Here is macro for you, that will provide you identical functionality.

Sub NullCheck()
    Dim selected As String
    Dim var As String
    Dim res As String
    Dim sel As TextSelection

    sel = DTE.ActiveDocument.Selection
    selected = sel.Text        
    var = selected.Substring(0, selected.IndexOf("=") - 1).Trim()
    res = String.Format("if ({0} == null) {1} ", var, selected)

    sel.Insert(res, vsInsertFlags.vsInsertFlagsContainNewText)

End Sub

The alternative (after reading your comment) may be to use PostSharp in order to intercept field/property setter.

share|improve this answer
v. nice - I've never used the macros before. I added a WrapInBrackets function to get past the stylecop: Function WrapInBrackets(ByVal var, ByVal selected) Dim res As String res = String.Format("if ({0} == null)", var) res = res & vbCrLf & "{" res = res & vbCrLf & selected res = res & vbCrLf & "}" WrapInBrackets = res End Function –  burnside Apr 21 '09 at 12:35

Assuming CREATEDATE is a property, why don't you move this logic over there?

    set { _createdate = value ?? DateTime.Now; }

or use the same ?? operator outside setter:

accgrp.CREATEDATE = accgrp.CREATEDATE ?? DateTime.Now;
share|improve this answer
nice approach, i'd forgotten about the ?? operator. however i can't move the logic to the setter as accgrp is an entity in the entity framework. for every property on the entity i need to set a default where the user has entered no value. i understand that there's a defaultvalue property in the ef designer, but it can't take functions. your second suggestion is cool, but still suffers from not being able to use $selected$ twice in a snippet –  burnside Apr 21 '09 at 12:05

Your Answer


