Shortcut to creating many properties all with default get / set body

22,492

Solution 1

In C# 3 or higher, you can use auto-implemented properties:

public int MyInt { get; set; }

Solution 2

In VS2010 & 2008 you can right click on the private field, select Refactor->Encapsulate Field.

You will still have to do it field by field, but it has got some smarts in it (with regards to choosing a publicly viewable name), and you can do it all with no typing.

Follow up: i see that the answer from Josh M shows you the keyboard shortcut to do the same thing.

Solution 3

Try CTRL+R+E while on the field.

See more great shortcuts in this blog post.

Solution 4

Instead of using fields use properties to begin with:

public int MyInt { get; set }
public DateTime SomeDate { get; set; }
Share:
22,492
DRapp
Author by

DRapp

C# for the past 10+ yrs, but started in '85, primarily focused using FoxPro / Visual Foxpro systems. Almost all work has been desktop database applications. Some recent work (5yrs) working with handheld scanner devices with Windows Mobile CE and most recently C#.net Xamarin for Android devices.

Updated on January 02, 2020

Comments

  • DRapp
    DRapp over 4 years

    Is there some shortcut way of handling multiple properties on a class (say 50 spanning string, int, datetime, etc). They will all have the same simple declaration such as

    private int myInt;
    public int MyInt 
    { get { return myInt; }
      set { myInt = value; }
    }
    
    private datetime someDate;
    public datetime SomeDate
    { get { return someDate; }
      set { someDate = value; }
    }
    

    The reason, is I have a class that will be "bound" to data entry textbox type fields and such. By just making them "public" doesn't work as it wont bind to a field, but will if it's a property with applicable get/set. I just think it's a pain to go through such efforts when it's the same repetition over and over, and believe there is a shorter / more simplified method. I just don't have another mentor to learn from and know that S/O has plenty to help out.

    For the current situation I'm in, requires me to only work with .Net 2.0 max... Some restrictions based on handheld devices not yet capable of running 3.0, 3.5, etc.