Search code examples
c#vb.netooppropertiesgetter-setter

Class Fields in VB.NET can be encapsulated without the Getter & Setter?


In a VB.NET I noticed that I'm able to create a property directly by using the Property keyword followed by the property name and the datatype without the need for the getter and setter method while I can't do this in C#!

Nevertheless, this property seems to be encapsulated as if I were put it in a getter and setter method!

Please take a look at the below screenshot.

enter image description here

In the screenshot above, the property I'm talking about is the number1, and I've created another property encapsulated in a getter and setter method called number2.

Then, I've created a new instance of the Class1 in the Class2, but I've noticed that the number1 property isn't exposed until I've created an instance of its class which is the same as if it was encapsulated in a getter and setter method like the number2 property!

Any explanations?


Solution

  • This is called an "auto property", and is pretty clearly defined in the VB.NET documentation:

    Public Property Name As String
    Public Property Owner As String = "DefaultName"
    Public Property Items As New List(Of String) From {"M", "T", "W"}
    Public Property ID As New Guid()
    

    Are all auto-properties with both a getter and setter (and an automatically created backing-field).

    C# requires you to use the {get; set;} but is basically the same (because C# doesn't have the Property keyword, it needs something to differentiate it between a field and a property, so the {get; set;} does that). C# is a little different though in that you can define getter-only properties without the {get; set;}...

    public int MyProperty => 10;
    

    Would be equivalent to

    public int MyProperty { get { return 10; } }