With reSharper -> Edit -> Generate Code -> Properties from this:
private int _age;
I get this
public int Age
{
get { return _age; }
set { _age = value; }
}
which is alright, but what can I do if I want something like this:
public int Age
{
get { return _age; }
set
{
if (_age != value)
{
_age = value;
OnPropertyChanged("Age");
}
}
}
Is there a way to customise ReSharper's output? FYI I'm on Visual Studio 2008, ReSharper v5.1.
You could write your own ReSharper Live Template like so:
Then you can enter new properties with backing field and OnPropertyChangedEvent call by one step by typing in first letters of live template shortcut: propWithChangeEvents.
Then an intellisence list appears. You select propWithChangeEvents, type the field type (i.e. int) and ENTER, then field name (i.e. age) and ENTER.
Then all is generated as you need.
That's for new fields/properties. If you really need the same for existing fields let me know it.
You could create a live template to do what you want. I have a couple templates I use for custom property implementations. It's pretty powerful stuff.
Related
I am making an app in Flutter and i am using Android studio for that. But it is not making getter and setter by using alt+insert command to generate getter and setter automatically.is there any way of doing this?
You don't need that in Dart.
A field is equivalent to a getter/setter pair.
A final field is equivalent to a getter.
You change it only to actual getters/setters if additionally logic is required and this change is non-breaking for users of that class.
Public getter/setter methods for private fields is an anti-pattern in Dart if the getters/setters don't contain additional logic.
class Foo {
String bar; // normal field (getter/setter)
final String baz; // read-only (getter)
int _weight;
set weight(int value) {
assert(weight >= 0);
_weight = value;
}
int get weight => _weight
}
I didn't clearly understand your questions but check if this helps.
String _myValue = "Hello World";
Now press Comman+N in mac and select Getter and Setter.
Now that you can see the Getter and Setter generated for you.
String _myValue = "Hello World";
String get myValue => _myValue;
set myValue(String value) {
_myValue = value;
}
Ensure that you use "_" as a prefix for the private variables.
To understand getter and setter in dart follow this youtube video.
EDIT:
Noticing the higher votes for my answer, I'm responsible to clarify a few things here. As rightly mentioned by Günter Zöchbauer, explicit getter/setter declarations are not necessary for Dart.
In Android studio:
Right click on the variable name on the line where you declare it.
Click on "Show Context Actions" or Option + Enter on Mac
Then click on "Encapsulate Field".
Android Studio Dart
I was also stuck on the same, I found out that we have to declare our private variable names with an underscore ( _TestVariable ).
Then use the shortcut Alt + insert (On Windows) to generate automatic Getters/Setters
class Books
{
late int _id;
int get id => _id;
set id(int value) {
_id = value;
}
}
I have a situation where I want the variable to be capitalized for documentation eg
(trivalized for example)
///AT+$COMMAND$
void At$COMMAND$()
{
}
So I want the user of the template to type in something like "Blah" and that gets used in the method name, but the documentation part gets changed to "BLAH".
eg
///AT+BLAH
void AtBlah()
{
}
Can I do this? I see in the macros I can capitalize the first letter, but I'd like the whole word capitalized. Is it possible to create custom macros?
They just updated documentation to meet changes in macros in Resharper 8. You can check it at http://confluence.jetbrains.com/display/NETCOM/4.04+Live+Template+Macros+%28R8%29
With the new docs it is quite easy, my implementation goes here:
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using JetBrains.DocumentModel;
using JetBrains.ReSharper.Feature.Services.LiveTemplates.Macros;
using JetBrains.ReSharper.Feature.Services.LiveTemplates.Hotspots;
namespace ReSharperPlugin
{
[MacroDefinition("LiveTemplatesMacro.CapitalizeVariable", // macro name should be unique among all other macros, it's recommended to prefix it with your plugin name to achieve that
ShortDescription = "Capitalizes variable {0:list}", // description of the macro to be shown in the list of macros
LongDescription = "Capitalize full name of variable" // long description of the macro to be shown in the area below the list
)]
public class CapitalizeVariableMacro : IMacroDefinition
{
public string GetPlaceholder(IDocument document, IEnumerable<IMacroParameterValue> parameters)
{
return "A";
}
public ParameterInfo[] Parameters
{
get { return new[] {new ParameterInfo(ParameterType.VariableReference)}; }
}
}
[MacroImplementation(Definition = typeof(CapitalizeVariableMacro))]
public class CapitalizeVariableMacroImpl : SimpleMacroImplementation
{
private readonly IMacroParameterValueNew _parameter;
public CapitalizeVariableMacroImpl([Optional] MacroParameterValueCollection parameters)
{
_parameter = parameters.OptionalFirstOrDefault();
}
public override string EvaluateQuickResult(IHotspotContext context)
{
return _parameter == null ? null : _parameter.GetValue().ToUpperInvariant();
}
}
}
I've got an IClaimsPrincipal variable, and I'd like to see how many claims are in it. Navigating through the properties in the watch window is complicated, so I'd like to customize how this object is displayed.
I'm aware of the [DebuggerTypeProxy] attribute, which initially looked like it might do what I want. Unfortunately, it needs to be attached to the class, and I don't "own" the class. In this case it's a Microsoft.IdentityModel.Claims.ClaimsPrincipal.
I'd like to display the value of IClaimsPrincipal.Identities[0].Claims.Count.
Is there any way, using [DebuggerTypeProxy] or similar, to customize how the value of a type that I don't own is displayed in the watch window?
Example of DebuggerTypeProxyAttribute applied to KeyValuePair showing only the Value member:
using System.Collections.Generic;
using System.Diagnostics;
[assembly: DebuggerTypeProxy(typeof(ConsoleApp2.KeyValuePairDebuggerTypeProxy<,>), Target = typeof(KeyValuePair<,>))]
// alternative format [assembly: DebuggerTypeProxy(typeof(ConsoleApp2.KeyValuePairDebuggerTypeProxy<,>), TargetTypeName = "System.Collections.Generic.KeyValuePair`2")]
namespace ConsoleApp2
{
class KeyValuePairDebuggerTypeProxy<TKey, TValue>
{
private KeyValuePair<TKey, TValue> _keyValuePair; // beeing non-public this member is hidden
//public TKey Key => _keyValuePair.Key;
public TValue Value => _keyValuePair.Value;
public KeyValuePairDebuggerTypeProxy(KeyValuePair<TKey, TValue> keyValuePair)
{
_keyValuePair = keyValuePair;
}
}
class Program
{
static void Main(string[] args)
{
var dictionary = new Dictionary<int, string>() { [1] = "one", [2] = "two" };
Debugger.Break();
}
}
}
Tested on Visual Studio 2017
The best I've come up with so far is to call a method:
public static class DebuggerDisplays
{
public static int ClaimsPrincipal(IClaimsPrincipal claimsPrincipal)
{
return claimsPrincipal.Identities[0].Claims.Count;
}
}
...from the watch window:
DebuggerDisplays.ClaimsPrincipal(_thePrincipal),ac = 10
The ",ac" suppresses the "This expression causes side effects and will not be evaluated".
However, note that when this goes out of scope, Visual Studio will simply grey out the watch window entry, even with the ",ac". To avoid this, you'll need to ensure that everything is fully qualified, which means that you'll end up with extremely long expressions in the watch window.
currently the code which i have is generating the properties like
private int integerProperty
{
get
{
return integerField;
}
set
{
integerField = value;
}
}
I wanted the properties to be simple like...
private int integerProperty
{
get;
set;
}
The code i have with me is
CodeMemberProperty property1 = new CodeMemberProperty();
property1.GetStatements.Add(new CodeMethodReturnStatement(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "integerField")));
property1.SetStatements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "integerField"),new CodePropertySetValueReferenceExpression()));
type1.Members.Add(property1);
Anyone please help. Thanks in advance.
As Botz3000 mentioned, it's officially not possible. However, with the following hack you can implement it:
var field = new CodeMemberField
{
Attributes = MemberAttributes.Public | MemberAttributes.Final,
Name = "MyProperty",
Type = new CodeTypeReference(typeof(MyType)),
};
field.Name += " { get; set; }";
By appending { get; set; } to the field name, it will generate a property in the actual source code.
This is an old question, but is worth noting that the answer by "#Serguei Fedorov" is no longer applies (it's valid only for c# 1.0 to c# 2.0)
The solution of replacing "};" with "}" should be avoid, because "};" is used for the syntax of Object and Collection Initializers starting from C# 3.0.
Review Object and Collection Initializers.
Example:
var pet = new { Age = 10, Name = "Fluffy" }; //it's ended by "};"
Alternative solution
You can use the new .NET Compiler Platform ("Roslyn") which support C# 1.0 to c#6.0.
The samples include ConvertToAutoProperty - A code refactoring to change a simple property with a trivial getter and setter into an auto property.
If you interested by CodeDom, there's a new CodeDOM Providers for .NET Compiler Platform (“Roslyn”) that can be installed from nuget
No, it's not possible. Automatic properties are a language specific feature, so you won't find any way to generate those.
whats difference between Auto-Implemented Properties and manual properties in c#?
for Example:
Manual Properties:
private int uno;
public int Uno
{
get { return uno; }
set { uno = value; }
}
Auto Implemented Prop:
public string UserLeaveCount { get; set; }
i found the difference and uses here : Auto Implemented Prop
But Here is my Specific doubt thats "there is no instance variable in auto implemented properties and how is it stored,returned values?"
It's just syntactic sugar -- the compiler inserts the backing field for you. The effect is the same, except that, of course, there's no way for you to access the backing field from your code.
From the page you linked to:
When you declare a property as shown in the following example, the compiler creates a private, anonymous backing field that can only be accessed through the property's get and set accessors.