Geeks With Blogs


Add to Google

Tim Hibbard CEO for EnGraph software

This code snippet extends the functionality found in prop code snippet.  It will populate the backing field in the property, check for equality in the setter and call PropertyChanged.  It assumes you have a base class that handles the implementation of INotifyPropertyChanged.

When the snippet is called, it will generate code that looks like this:

private int myVar;
public int MyProperty
    get { return myVar; }
        if (!myVar.Equals(value))
            myVar = value;

To use this snippet, create a new text file at:
C:\users\<your user name>\Documents\Visual Studio 2008\Code Snippets\Visual C#\My Code Snippets

Call it “propINP.snippet”

Populate the contents of the file with this:

<?xml version="1.0" encoding="utf-8"?>
<CodeSnippets xmlns="">
  <CodeSnippet Format="1.0.0">
      <Author>Microsoft Corporation</Author>
      <Description>Code snippet for property and backing field and INotifyPropertyChanged</Description>
        <Literal Editable="true">
          <ToolTip>Property type</ToolTip>
        <Literal Editable="true">
          <ToolTip>Property name</ToolTip>
        <Literal Editable="true">
          <ToolTip>The variable backing this property</ToolTip>
      <Code Language="csharp"><![CDATA[private $type$ $field$;
public $type$ $property$
get { return $field$;}
$field$ = value;

Posted on Tuesday, November 18, 2008 2:19 PM .NET , Keyboard Shortcuts | Back to top

Comments on this post: VS2008 code snippet for Properties that support INotifyPropertyChanged

# re: VS2008 code snippet for Properties that support INotifyPropertyChanged
Requesting Gravatar...

Thanks for posting this. However, there is an issue with it in that if the current value of the property is null (which is most of the time during initialisation), using the Setter causes a null ref exception - as it tries to do myVar.Equals.

When the type is a string, I've been replacing the check with

!String.Equals(myVar, value)

(obviously, this doesn't take into consideration culture etc).

For other types, I just replaced it with a simple

myVar != value

Having thought about it - I guess I could use that check too for strings.

Left by Lee Oades on Mar 10, 2009 6:55 AM

Your comment:
 (will show your gravatar)

Copyright © Tim Hibbard | Powered by: