Code - Investing - FI

Visual Basic/C# Tutorial 18 – Properties

Properties define the class, they are self contained variables that you can either read and/or write. They are there to make sure that the class remains valid. You have to remember two important words:

1. Get -> retrieve a value from inside of the object.
2. Set -> Assign a value inside of the object.

We’ve seen the short and the long version of Property declaration, but now we will dive a bit more in the subject.

New Class

Let’s define a new class with 3 properties to work with.

Visual Basic

Public Class Mouse
    Public Property Color As String
    Public Property NumberOfButtons As Integer
    Public Property HasLEDs As Boolean

    Public Sub New()
        Color = "Black"
        NumberOfButtons = 3
        HasLEDs = True
    End Sub
End Class

C#

using System;

namespace PropertiesCSharp
{
    public class Mouse
    {
        public string Color { get; set; }
        public int NumberOfButtons { get; set; }
        public Boolean HasLEDs { get; set; }

        public Mouse(string Color, int NumberOfButtons, Boolean HasLEDs)
        {
            this.Color = Color;
            this.NumberOfButtons = NumberOfButtons;
            this.HasLEDs = HasLEDs;
        }
    }
}

In this case, our properties are all public, so we can access them for reading and writing. Sometimes you might not want that behavior since properties are there to expose some values and some not. This will restrain the access to our class processing private variables that we might want to block from the outside world.

Lets Make it Private!

Lets say we don’t want to user to be able to set the NumberOfButtons and HasLEDs values. Then we will have to change the format of our properties a little and use local variables. Here is a way to accomplish this task.

Visual Basic

Option Explicit On
Option Strict On

Public Class Mouse
    Private _NumberOfButtons As Integer
    Private _HasLEDs As Boolean

    Public Property Color As String
    Public Property NumberOfButtons As Integer
        Get
            Return _NumberOfButtons
        End Get
        Private Set(ByVal value As Integer)
            _NumberOfButtons = value
        End Set
    End Property
    Public Property HasLEDs As Boolean
        Get
            Return _HasLEDs
        End Get
        Private Set(ByVal value As Boolean)
            _HasLEDs = value
        End Set
    End Property

    Public Sub New()
        Color = "Black"
        NumberOfButtons = 3
        HasLEDs = True
    End Sub
End Class

C#

using System;

namespace PropertiesCSharp
{
    public class Mouse
    {
        private int _NumberOfButtons;
        private bool _HasLEDs;

        public string Color { get; set; }
        public int NumberOfButtons
        {
            get
            {
                return _NumberOfButtons;
            }
            private set
            {
                _NumberOfButtons = value;
            }
        }
        public bool HasLEDs
        {
            get
            {
                return _HasLEDs;
            }
            private set
            {
                _HasLEDs = value;
            }
        }

        public Mouse(string Color, int NumberOfButtons, Boolean HasLEDs)
        {
            this.Color = Color;
            this.NumberOfButtons = NumberOfButtons;
            this.HasLEDs = HasLEDs;
        }
    }
}

Both properties mentionned above are now expanded (long version), and the Set statement is Private, which will not permit the user of the object to access these two statements, in other words to write to NumberOfButtons and HasLEDs in order to modify their value. You can change the Get to private as well but it won’t be really useful since the user will not be able to access the value at all.

Note: remember that the private keyword makes it possible to restrain access to different parts of the class, not just properties, it can apply to methods and constructors as well!

Visual Basic

Private Property

C#

C Sharp Property Access

As you can see, we cannot assign anything to HasLEDs because it is now private!

What is the “value” in the long version?

The value variable contains what as been assigned from the user to this property in the Set statement. It’s more explicit in Visual Basic because in C# we cannot see exactly where this value comes from.

Visual Basic

Property value statement

C#

C Sharp property value

The image above shows that the value I assigned in the constructor (3) has been assigned to value at runtime, which is what I explained.

Note: in Java, properties are methods defined with the prefix get or set, I am sure you’ve noticed that properties look a bit like methods in the way they are accessed, you’re right! But they have been modified to be more intuitive in Visual Basic and C#.

Why using the long version over the short version?

Sometimes you just want to make a class property accessible from outside, but other times you might want to give the user a bit more options. For example, in the case that the property is not actually a real variable but calculated as the user retrieves the value. Here is an example of such behavior.

Visual Basic

    Public ReadOnly Property LightsAreOn As Boolean
        Get
            If HasLEDs Then
                Return True
            Else
                Return False
            End If
        End Get
    End Property

C#

        public bool LightsAreOn
        {
            get
            {
                if (_HasLEDs)
                    return true;
                return false;
            }
        }

As you can see, this property does not encapsulate a variable, it’s strictly based on the fact that if the Mouse has LED lights, they are on, if not, then they are off. Notice that you have to write ReadOnly(Visual Basic) because no set statement is present (WriteOnly if only the set statement is present).

Access properties from outside

If you create a real object from the class we just completed, you can access the properties. Here is an example:

Visual Basic

New Mouse example class

C#

Mouse usage class

You can easily access any property by simply typing NameOfTheVariable.Property and assign it with NameOfTheVariable.Property = ValueToAssign.

Conclusion

Properties are ways to control access to what defines a class, they can be declared in the short or long version depending on what you intend to do. Set and Get are important keywords to remember along with public and private to limit the user access to the values. Again, the best way to really understand Properties is to play with them directly in the IDE and with the Debug mode, put breakpoints and try to assign and retrieve values from them!

In the next tutorial, we’re going to talk about the methods and there will be an exercise on classes later!

Visual Basic

C#

Next article Visual Basic/C# Tutorial 19 - Methods
Previous article Visual Basic/C# Tutorial 17 - Constructors

Related posts