C#.NET - Initialize auto-properties in Visual Studio 2008 like 2005
If you're like me, you like to use the "prop" snippet from Visual Studio 2005. If you don't know what I'm talking about, with a C# file open in Visual Studio 2005 (or 2008), type:
However, in 2008, prop tab tab gives you the following..
This is a problem because there's no simple quick way to initialize the variable.
You can initialize it in a constructor, but what if you're using a static class? You're only other option is to use a DefaultValue attribute like so:
The problem with using the DefaultValue attribute is that, as far as I know, it requires using Reflection. So not only is it a pain to type, you also take a performance hit.
The way that 2005 handled it still works in 2008, so the easiest solution is to use the snippet from 2005 in 2008. I have created a propx snippet to handle just that. Simply unzip and put the propx.snippet file into your My Code Snippets folder (in Windows 7 this is located at C:\Users\Gordon\Documents\Visual Studio 2008\Code Snippets\Visual C#\My Code Snippets\), restart visual studio then type propx tab tab to use it.
prop then hit tab twice. In 2005, you are able to initialize the variable like so:private string _name = "default"; public string Name { get { return _name; } set { _name = value; } }
However, in 2008, prop tab tab gives you the following..
public string Name { get; set; }
This is a problem because there's no simple quick way to initialize the variable.
You can initialize it in a constructor, but what if you're using a static class? You're only other option is to use a DefaultValue attribute like so:
[DefaultValue("default")] public string Name { get; set; }
The problem with using the DefaultValue attribute is that, as far as I know, it requires using Reflection. So not only is it a pain to type, you also take a performance hit.
The way that 2005 handled it still works in 2008, so the easiest solution is to use the snippet from 2005 in 2008. I have created a propx snippet to handle just that. Simply unzip and put the propx.snippet file into your My Code Snippets folder (in Windows 7 this is located at C:\Users\Gordon\Documents\Visual Studio 2008\Code Snippets\Visual C#\My Code Snippets\), restart visual studio then type propx tab tab to use it.
Comments: (0)
alphatrak
Bringing you the coding smackdown since '95
Bringing you the coding smackdown since '95
Now Playing
- StarCraft - PC
Now Reading
- Death Note
- Ikigami: The Ultimate Limit
- Infinite Game Universe: Mathematical Techniques
- Microserfs by Douglas Coupland
- Pro Android 2