Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Resharper convert auto-property to full property

I found the opposite here, but I need to frequently change from auto-property to full property - would it be possible to automate that (and with a shortcut perhaps):

From Auto-Property

public string FirstName { get; set; }

To Property with Backing Field

    private string _firstName;

    public string FirstName
    {
        get
        {
            return _firstName;
        }
        set
        {
            _firstName = value;
        }
    }

Obviously, I would then change the full property further ...

like image 391
Cel Avatar asked May 23 '12 19:05

Cel


3 Answers

Place your cursor on the property name, then wait a second or two. Press the Resharper hotkey sequence (Alt-Enter) and the second option should be "To property with backing field" which is what you want.

Alternatively, you can click the "hammer" icon in the left margin to get the option.

like image 127
Dan Morphis Avatar answered Nov 09 '22 19:11

Dan Morphis


To make it work (ALT-Enter) you must to configure resharper keyboard schema. VS -> Tools -> Options -> ReSharper -> General -> Options -> Keyboard and menus -> Resharper keyboard Schema -> Visual Studio

like image 34
user3520366 Avatar answered Nov 09 '22 19:11

user3520366


I would like to add an extended solution which also allows to create a property in this style, that has support for INotifyPropertyChanged for viewmodels:

public string Name
{
    get => _name;
    set
    {
        if (value == _name) return;
        _name = value;
        RaisePropertyChanged();
    }
}

/// <summary>
/// Raises the <see cref="PropertyChanged"/> event for the given <paramref name="propertyName"/>.
///
/// The <see cref="NotifyPropertyChangedInvocatorAttribute"/> attribute is used
/// because of Resharper support for "to property with change notification":
/// https://www.jetbrains.com/help/resharper/Coding_Assistance__INotifyPropertyChanged_Support.html
/// </summary>
/// <param name="propertyName"></param>
[NotifyPropertyChangedInvocator]
public virtual void RaisePropertyChanged([CallerMemberName] string propertyName = null)
{
    PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}

The required steps are:

  • Install the Nuget package "JetBrains.Annotations" in the project were your viewmodels are located
  • Use the [NotifyPropertyChangedInvocator] attribute on the method where the PropertyChanged event is raised
  • After that, the option "To property with change notification" is available for the properties of your viewmodels

enter image description here


See also: Jetbrains INotifyPropertyChanged support

like image 1
Martin Avatar answered Nov 09 '22 20:11

Martin