Class properies

Property

A property is the mechanisme wich allows us to set or get the value of a field. A propertie ( getter and setter ) returns the value of a private field or set the value of the private field:

    public class Student
    {
        // private
        private string studentName = string.Empty;

        // properties
        public int StudentID { get; set; }

        public string StudentName
        {
            get
            {
                return studentName;
            }
            set
            {
                studentName = value;
            }
        }

        public DateTime? DateOfBirth { get; set; }

        // ctor
        public Student(){}
    }

Read only property

A read only property is a property without a setter. It just returns the value of the private field.

    public class Student
    {
        // private
        private string studentName = "Teus";

        // properties
        public int StudentID { get; set; }

        public string StudentName
        {
            get
            {
                return studentName;
            }
        }

        public DateTime? DateOfBirth { get; set; }

        // ctor
        public Student(){}
    }

Auto property

In C# 3 auto property is implemented. This maken the life of a programmer easier again. With auto properties a propertie doesn't need to have a private field to store or return the value. Just a property with StudentName is enough to be able to retrieve or store the student name.

    public class Student
    {

        // properties
        public int StudentID { get; set; }

        public string StudentName { get; set; }

        public DateTime? DateOfBirth { get; set; }

        // ctor
        public Student(){}
    }

Read only auto property

In C# 6 there is a new kind of property: the read only auto property wich is a auto propery wich is read only

    public class Student
    {

        // properties
        public int StudentID { get; set; }

        public string FirstName { get; }

        public string LastName { get;  }

        public DateTime? DateOfBirth { get; set; }

        // ctor
        public Student(){}

        public Student(string firstname, string lastname)
        {
            if (string.IsNullOrWhiteSpace( lastname )) throw new ArgumentException(message: "Cannot be blank", paramName: nameof(lastname));

            FirstName = firstname;
            LastName = lastname;
        }
    }

A read only auto propery is a property which value only can be set in the constructor of the object. Read only auto properties are now easier to write and function better than the old skool properties with private setters and private field values.

{{opmerking.Naam}}:

{{opmerking.OpmerkingText}}

            

Saving your comment....

Naam is verplicht!
Email is verplicht!
Opmerking is verplicht!