Search code examples
c#propertiesgetset

C# set and get shortcut properties


I'm watching an instructional video on C# and they showed a shortcut (type "prop", tab twice) it generates this

public int Height { get; set; }

So then he went on a shortcut about using => instead of this. It tried to combine the two but got an error in Length:

    class Box
{
    private int length;
    private int height;
    private int width;
    private int volume;

    public Box(int length, int height, int width)
    {
        this.length = length;
        this.height = height;
        this.width = width;
    }


    public int Length { get => length; set => length = value; } // <-error
    public int Height { get; set; }
    public int Width { get; set; }
    public int Volume { get { return Height * Width * Length; } set { volume = value; } }

    public void DisplayInfo()
    {
        Console.WriteLine("Length is {0} and height is {1} and width is {2} so the volume is {3}", length, height, width, volume = length * height * width);
    }

}

Volume works fine, but I was interested in seeing if I can shorten the code like I'm trying to do with Length.

  1. What am I doing wrong, can it be done that way? 2. Is there a shorter was to set properties (am I on the right track)

Solution

  • You can use the => expression-bodied member syntax as a shortcut for read-only properties in C# 6.0 (you can't use them with a set) and in C# 7.0 they were expanded to include set accessors as you have in your code (which require backing fields, also as you have).

    Most likely you're on C#6 so you're getting an error on the set syntax.

    You asked how to shorten your code, and since you don't have a need for a private backing member (you aren't modifying the value in the set or get accessors), it would be shortest to get rid of them and just use auto-implemented properties for the ones that the user can set. Then you can use => for the Volume property, since it should be read-only (because it's a calculated field):

    I believe this is the shortest code for the class you've described:

    class Box
    {
        public int Length { get; set; }
        public int Height { get; set; }
        public int Width { get; set; }
        public int Volume => Height * Width * Length;
    
        public Box(int length, int height, int width)
        {
            Length = length;
            Height = height;
            Width = width;
        }
    
        public void DisplayInfo()
        {
            Console.WriteLine("Length = {0}, Height = {1}, Width = {2}, Volume = {3}", 
                Length, Height, Width, Volume);
        }
    
    }