When I use autoproperty for example
public string Prop {get;set;}
compiler generates two functions: get_Prop() and set_Prop(string val). I would like to set breakpoint on one from this function. When I set breakpoint by function this function name debuger never enter in this functions. Intellisense doesn't work in my dialog (Ctrl+B)
My questions:
1) Where compiler save source code with replaced property to function? If it do this.
2) Why Intelisense not working?
3) How to set breakpoint on this functons?
I use VS2013 Ultimate.
1) the compiler don't save source code, it compiles. The implicit backing fields are only present in the IL code.
2) It's a feature, not a bug, I agree it could be great.
3) You have to create a backing field manually in order to put a breakpoint on it.
private string _prop;
public string Prop
{
get { return _prop; }
set { _prop= value; }
}
There is a great solution described here:
Debugging automatic properties
Basically, you can set a breakpoint with Breapooint->Create New and put it on
ClassName.set_PropertyName
or
ClassName.get_PropertyName.
It is also available in Visual Studio 2015, or for earlier versions you can use VS plugins such as Oz Code to do this automatically (break on setter)
namespace Guilds
{
public class Wizard
{
public void Wear(IClothing clothing)
{
Console.WriteLine("Puts on the {Robe} and {WizardHat}".Fmt(clothing));
}
IClothing _clothes;
IWeapon _weapon; // <== I want my fields added at the bottom of the class!
}
}
I am aware that if you put your fields at the bottom, it will start adding subsequent ones to the bottom of the class as well. I would love to have this as the default behavior even for the first field.
This behavior is usually triggered when pressing Ctrl + . on top of an undeclared field.
Use Regionerate and create your own format template. it's free tool to use with visual studio.
Edit: You can also use CodeMaid because it seems that Regionerate and VS2012 do not work together (I have not tested that combination at all though. I have VS2010)
Edit Adding more to my previous reply. CodeMaid is really cool and you can specify the layout in configuration. Also in configuration, you can specify that file should be formatted on save. This way write your code in anyway you want and have it formatted when you press Ctrl+S! I am one happy user of CodeMaid. Also I am using Visual Studio 2013.
When I write code and need new property, i simply write propery name as it would exist already and choose action from menu:
Problem is, that it generates code like this:
protected int SomeNewProperty
{
get { throw new System.NotImplementedException(); }
set { throw new System.NotImplementedException(); }
}
So I need to go there and manually adjust that (actually I prefer to choose Create field from menu and change it to auto property). Anyway, I thought, may be there is a way to change default behavior of "Create property", that it would create auto property instantly?
Update
In Resharper 8 auto properties are available and may be set by default!
You cannot do this in R# (at least in v6). That is, create a pseudo property and have resharper generate the Auto Property stub.
You can still use the superior method that Visual Studio uses. Type out your new property which will show as a syntax error and then CTRL + . shows VS mini menu. Then just hit enter and straight away, the job is done.
It does not take you to the class file which can be distracting too. To use the shortcut above, you don't even need to have you cursor on the broken property name.
So this is better than the method described by Rickard as it is faster and less distracting you away from the code you are writing.
Just when you click Create property it will halt on the type. Hit tab and you will get a context menu with the option to use Auto property.
There is an option to change default body style.
However, the close you can get is
protected int SomeProperty
{
get { return 0; }
set { }
}
There is a default snippet that comes with Visual Studio called 'prop' Just type that, hit , give a type name and give it a name. Done and done.
I know that doesn't answer your question in terms of Resharper, but it is functionality already provided by the Visual Studio IDE.
I am trying to get started in Visual Studio (2010) extensions and I am having a hard time finding the right materials. I have the SDK, but the included samples seem to be things like adorners, windows, and icons.
I am trying to make an extension that will work directly with the text editor (to alphabetize all of my method names in a class, or make all constant names upper case for example) but I can't find a demo for this type of functionality, or even a tutorial.
Does anyone know where I can find this kind of stuff?
I had the exact same question and now have browsed the web several hours until I was being able to understand and explain how you'd need to start with such an extension.
In my following example we will create a small and dumb extension which will always add "Hello" to the beginning of a code file when an edit has been made. It's very basic but should give you an idea how to continue developing this thing.
Be warned: You have to parse the code files completely on your own - Visual Studio does not give you any information about where classes, methods or whatever are and what they contain. That's the biggest hurdle to be taken when doing a code formatting tool and will not be covered in this answer.[*]
For those who skipped to this answer, make sure you downloaded and installed the Visual Studio SDK first or you will not find the project type mentioned in step one.
Creating the project
Start by creating a new project of the type "Visual C# > Extensibility > VSIX Project" (only visible if you selected .NET Framework 4 as the target framework). Please note that you may have to select the "Editor Classifier" project type instead of the "VSIX Project" type to get it working, s. comment below.
After the project has been created, the "source.extension.vsixmanifest" file will be opened, giving you the ability to set up product name, author, version, description, icon and so on. I think this step is pretty self-explaining, you can close the tab now and restore it later by opening the vsixmanifest file.
Creating a listener class to get notified about text editor instance creations
Next, we need to listen whenever a text editor has been created in Visual Studio and bind our code formatting tool to it. A text editor in VS2010 is an instance of IWpfTextView.
Add a new class to our project and name it TextViewCreationListener. This class has to implement the Microsoft.VisualStudio.Text.Editor.IWpfTextViewCreationListener interface. You need to add a reference to Microsoft.VisualStudio.Text.UI.Wpf to your project. The assembly DLL is found in your Visual Studio SDK directory under VisualStudioIntegration\Common\Assemblies\v4.0.
You have to implement the TextViewCreated method of the interface. This method has a parameter specifying the instance of the text editor which has been created. We will create a new code formatting class which this instance is passed to later on.
We need to make the TextViewCreationListener class visible to Visual Studio by specifying the attribute [Export(typeof(IWpfTextViewCreationListener))]. Add a reference to System.ComponentModel.Composition to your project for the Export attribute.
Additionally, we need to specify with which types of files the code formatter should be bound to the text editor. We only like to format code files and not plain text files, so we add the attribute [ContentType("code")] to the listener class. You have to add a reference to Microsoft.VisualStudio.CoreUtility to your project for this.
Also, we only want to change editable code and not the colors or adornments around it (as seen in the example projects), so we add the attribute [TextViewRole(PredefinedTextViewRoles.Editable)] to the class. Again you need a new reference, this time to Microsoft.VisualStudio.Text.UI.
Mark the class as internal sealed. At least that's my recommendation. Now your class should look similar to this:
[ContentType("code")]
[Export(typeof(IWpfTextViewCreationListener))]
[TextViewRole(PredefinedTextViewRoles.Editable)]
internal sealed class TextViewCreationListener : IWpfTextViewCreationListener
{
public void TextViewCreated(IWpfTextView textView)
{
}
}
Creating a class for code formatting
Next, we need a class handling the code formatting logic, sorting methods and so on. Again, in this example it will simply add "Hello" to the start of the file whenever an edit has been made.
Add a new class called Formatter to your project.
Add a constructor which takes one IWpfTextView argument. Remember that we wanted to pass the created editor instance to this formatting class in the TextViewCreated method of our listener class (simply add new Formatter(textView); to the method there).
Save the passed instance in a member variable. It'll become handy when formatting the code later on (e.g. for retrieving the caret position). Also tie up the Changed and PostChanged events of the TextBuffer property of the editor instance:
public Formatter(IWpfTextView view)
{
_view = view;
_view.TextBuffer.Changed += new EventHandler<TextContentChangedEventArgs>(TextBuffer_Changed);
_view.TextBuffer.PostChanged += new EventHandler(TextBuffer_PostChanged);
}
The Changed event is called every time an edit has been made (e.g. typing a char, pasting code or programmatical changes). Because it also reacts on programmatical changes I use a bool determining if our extension or the user / anything else is changing the code at the moment and call my custom FormatCode() method only if our extension is not already editing. Otherwise you'll recursively call this method which would crash Visual Studio:
private void TextBuffer_Changed(object sender, TextContentChangedEventArgs e)
{
if (!_isChangingText)
{
_isChangingText = true;
FormatCode(e);
}
}
We have to reset this bool member variable in the PostChanged event handler again to false.
Let's pass the event args of the Changed event to our custom FormatCode method because they contain what has changed between the last edit and now. Those edits are stored in the array e.Changes of the type INormalizedTextChangeCollection (s. the link at the end of my post for more information about this type). We loop through all those edits and call our custom HandleChange method with the new text which this edit has produced.
private void FormatCode(TextContentChangedEventArgs e)
{
if (e.Changes != null)
{
for (int i = 0; i < e.Changes.Count; i++)
{
HandleChange(e.Changes[0].NewText);
}
}
}
In the HandleChange method we could actually scan for keywords to handle those in a specific way (remember, you have to parse any code on yourself!) - but here we just dumbly add "Hello" to the start of the file for testing purposes. E.g. we have to change the TextBuffer of our editor instance. To do so, we need to create an ITextEdit object with which we can manipulate text and apply it's changes afterwards. The code is pretty self-explaining:
private void HandleChange(string newText)
{
ITextEdit edit = _view.TextBuffer.CreateEdit();
edit.Insert(0, "Hello");
edit.Apply();
}
When compiling this add-in, an experimental hive of Visual Studio starts up with only our extension loaded. Create a new C# file and start typing to see the results.
I hope this gives you some ideas how to continue in this topic. I have to explore it myself now.
I highly recommend the documentation of the text model of the editor on MSDN to get hints about how you could do this and that.
http://msdn.microsoft.com/en-us/library/dd885240.aspx#textmodel
Footnotes
[*] Note that Visual Studio 2015 or newer come with the Rosyln Compiler Platform, which indeed already analyzes C# and VB.NET files for you (and probably other pre-installed languages too) and exposes their hierarchical syntactical structure, but I'm not an expert in this topic yet to give an answer on how to use these new services. The basic progress of starting an editor extension stays the same as described in this answer anyway. Be aware that - if you use these services - you will become dependent on Visual Studio 2015+, and the extension will not work in earlier versions.
just have a look at the "Getting started with Editor extensions" site on the MSDN http://msdn.microsoft.com/en-us/library/dd885122.aspx
Thorsten
By "generate", I mean auto-generation of the code necessary for a particular selected (set of) variable(s).
But any more explicit explication or comment on good practice is welcome.
Rather than using Ctrl + K, X you can also just type prop and then hit Tab twice.
Visual Studio also has a feature that will generate a Property from a private variable.
If you right-click on a variable, in the context menu that pops up, click on the "Refactor" item, and then choose Encapsulate Field.... This will create a getter/setter property for a variable.
I'm not too big a fan of this technique as it is a little bit awkward to use if you have to create a lot of getters/setters, and it puts the property directly below the private field, which bugs me, because I usually have all of my private fields grouped together, and this Visual Studio feature breaks my class' formatting.
I use Visual Studio 2013 Professional.
Place your cursor at the line of an instance variable.
Press combine keys Ctrl + R, Ctrl + E, or click the right mouse button. Choose context menu Refactor → Encapsulate Field..., and then press OK.
In Preview Reference Changes - Encapsulate Field dialog, press button Apply.
This is result:
You also place the cursor for choosing a property. Use menu Edit → Refactor → Encapsulate Field...
Other information:
Since C# 3.0 (November 19th 2007), we can use auto-implemented properties (this is merely syntactic sugar).
And
private int productID;
public int ProductID
{
get { return productID; }
set { productID = value; }
}
becomes
public int ProductID { get; set; }
By generate, do you mean auto-generate? If that's not what you mean:
Visual Studio 2008 has the easiest implementation for this:
public PropertyType PropertyName { get; set; }
In the background this creates an implied instance variable to which your property is stored and retrieved.
However if you want to put in more logic in your Properties, you will have to have an instance variable for it:
private PropertyType _property;
public PropertyType PropertyName
{
get
{
//logic here
return _property;
}
set
{
//logic here
_property = value;
}
}
Previous versions of Visual Studio always used this longhand method as well.
You can also use "propfull" and hit TAB twice.
The variable and property with get and set will be generated.
In visual studio 2019, select your properties like this:
Then press Ctrl+r
Then press Ctrl+e
A dialog will appear showing you the preview of the changes that are going to happen to your code. If everything looks good (which it mostly will), press OK.
If you are using Visual Studio 2005 and up, you can create a setter/getter real fast using the insert snippet command.
Right click on your code, click on Insert Snippet (Ctrl+K,X), and then choose "prop" from the list.
If you're using ReSharper, go into the ReSharper menu → Code → Generate...
(Or hit Alt + Ins inside the surrounding class), and you'll get all the options for generating getters and/or setters you can think of :-)
I created my own snippet that only adds {get; set;}. I made it just because I find prop → Tab to be clunky.
<?xml version="1.0" encoding="utf-8"?>
<CodeSnippets
xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
<CodeSnippet Format="1.0.0">
<Header>
<Title>get set</Title>
<Shortcut>get</Shortcut>
</Header>
<Snippet>
<Code Language="CSharp">
<![CDATA[{get; set;}]]>
</Code>
</Snippet>
</CodeSnippet>
</CodeSnippets>
With this, you type your PropType and PropName manually, then type get → Tab, and it will add the get set. It's nothing magical, but since I tend to type my access modifier first anyway, I may as well finish out the name and type.
In Visual Studio Community Edition 2015 you can select all the fields you want and then press Ctrl + . to automatically generate the properties.
You have to choose if you want to use the property instead of the field or not.
Use the propfull keyword.
It will generate a property and a variable.
Type keyword propfull in the editor, followed by two TABs. It will generate code like:
private data_type var_name;
public data_type var_name1{ get;set;}
Video demonstrating the use of snippet 'propfull' (among other things), at 4 min 11 secs.
In addition to the 'prop' snippet and auto-properties, there is a refactor option to let you select an existing field and expose it via a property (right click on the field → Refactor → Encapsulate Field...).
Also, if you don't like the 'prop' implementation, you can create your own snippets. Additionally, a third-party refactoring tool like ReSharper will give you even more features and make it easier to create more advanced snippets. I'd recommend ReSharper if you can afford it.
http://msdn.microsoft.com/en-us/library/f7d3wz0k(VS.80).aspx
Video demonstrating the use of snippet 'prop' (among other things), at 3 min 23 secs.
I don't have Visual Studio installed on my machine anymore (and I'm using Linux), but I do remember that there was an wizard hidden somewhere inside one of the menus that gave access to a class builder.
With this wizard, you could define all your classes' details, including methods and attributes. If I remember well, there was an option through which you could ask Visual Studio to create the setters and getters automatically for you.
I know it's quite vague, but check it out and you might find it.
On behalf of the Visual Studio tool, we can easily generate C# properties using an online tool called C# property generator.
First get Extension just press (Ctrl + Shift + X) and install getter setter ....
After this, just select your variable and right click. Go to Command palette...
And type getter ... It will suggest generate get and set methods. Click on this...
I personaly use CTRL+. and then select-
"Encapsulated Fildes".
That's a short for this option- (How can we generate getters and setters in Visual Studio?).
I marked the short for auto choosing refactoring (CTRL+. )
You just simply press Alt + Ins in Android Studio.
After declaring variables, you will get the getters and setters in the generated code.