CSharp’s Property Shortcuts

There are a lot of nice shortcuts in the CSharp language that most of us never use.  But if you take the time to learn them, you can be as productive as a student I had who had learned all the keyboard shortcuts to windows so that he never had to take his hands off the keyboard.

It was just a bit frustrating as an instructor because every time he sat down to do an exercise he’d be asking, “what’s the keyboard shortcut for this step?”  I have to admit, though, he was definitely faster than anyone else who had ever taken the class.

prop and propg are two such shortcuts.

If you are anything like me, I bet you write all of your properties something like this:

private int m_MyProperty;
public int MyProperty
{
    get { return m_MyProperty; }
    set { m_MyProperty = value; }
}

typing out every character.  Maybe you use a bit of copy and paste, but did you know that all you have to do is type:

prop

and you’ll get this:

image

Since my code insertion plugin won’t show you the full impact, I have to show you an image.

Basically it stubs out the property so all you have to do is supply the missing details.

propg gives you this:

image

The only difference is that it makes the getter private.

My preferred method is to create a member variable:

private int m_MyProperty;

Right click the variable and select “Refactor” > “Encapsulate Field…” from the context menu.  Once I’m done, I’m left with the code I typed above.

private int m_MyProperty;
public int MyProperty
{
    get { return m_MyProperty; }
    set { m_MyProperty = value; }
}

Related Post

  • Renaming Properties, Methods and VariablesRenaming Properties, Methods and Variables Have you ever written some code and named something one thing only to realize that it should be named something else? If you haven't you haven't been programming for very long.  Maybe you start...
  • Reflection – Calling PropertiesReflection – Calling Properties Today we'll continue our series on reflection by looking at Properties.  If you haven't already seen the videos on how to load the assembly or how to call the constructor, you'll probably want...
  • Two Time-saving VS Command Line ParametersTwo Time-saving VS Command Line Parameters I realize that many of my readers load one project at the beginning of the day and continue to work on only that project.  You guys won't benefit as much from this tip as those of us who switch be...
  • CSharp ?? OperatorCSharp ?? Operator One of the problems with learning a language early in its life cycle is that by the time version three comes out, you never look at or implement any of the new features. There are two reasons for ...
  • Readonly variables in CSharp? Really?!Readonly variables in CSharp? Really?! I'm sure most of you are familiar with the keyword "const," which allows you to declare a variable and give it a value and assures that no other code will change the value. const int v = 23; p...