-1

I am currently learning C#. I am stuck on the concept of properties. The doubt is if the following 2 codes are functionally equivalent, and if not, what is the implementational difference?


Code1

private int ivar;

public int ival {
    get { return ivar; }
    set { ivar = value; }
}

Code2

public int ival {
    get; set;
}

Which type of property form is used where?

kesarling He-Him
  • 1,944
  • 3
  • 14
  • 39
  • 2
    They are equal. Code2 is syntactical sugar of code1 – Chetan Jul 30 '20 at 04:05
  • 2
    The primary difference is that with the first one you can directly access the backing field within the class, but there's no real need for that in general so the second one basically means you write less code. – juharr Jul 30 '20 at 04:07
  • 1
    Its not security issue. The framework takes care of private variable internally. They are called Automatic properties. Microsoft wouldn't have introduced it if it was of no use. https://gunnarpeipman.com/csharp-automatic-properties/ – Chetan Jul 30 '20 at 04:07
  • 3
    With `{get;set;}` the C# compiler fills in the rest, creating the private field and the method bodies (hence "syntactic sugar"). There's lots of syntactic sugar in C#, stuff you could do by hand but don't need to. – Jeremy Lakeman Jul 30 '20 at 04:12

1 Answers1

2

They are exactly the same, the compiler generates the backing field for you, as seen here

You can also read more about Auto Properties from the documentation

In C# 3.0 and later, auto-implemented properties make property-declaration more concise when no additional logic is required in the property accessors. They also enable client code to create objects. 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.

Before

public int ival {get; set;}

Compiler generated

[CompilerGenerated]
private int <ival>k__BackingField;

public int ival
{
    [CompilerGenerated]
    get
    {
        return <ival>k__BackingField;
    }
    [CompilerGenerated]
    set
    {
        <ival>k__BackingField = value;
    }
}
TheGeneral
  • 79,002
  • 9
  • 103
  • 141