KodeBLOG

Kode Blog - Inspiring And Empowering Developers.

Home About Us Courses Categories Blog Contact Us

C# Class

Introduction

C# is an objected oriented programming language and makes heavy use of classes. In fact, almost anything in C# is an object. This tutorials introduces you to classes in C#.

Topics to be covered

  • What is a class?
  • How to define a class in C#
  • Class properties
  • C# Get Set
  • Class constructor
  • How to instantiate a class

What is a class?

A class is a blueprint for building real world objects such as people, products, cars etc. Let's explain this with the aid of an example, suppose you want to build a house, you start with a blueprint. The blueprint is like a template that you will use to build the actual house that you will live in. In object oriented programming terms, the house that you build from the blueprint is called an instance or object.

How to define a class in C#

The keyword class is used to define a class.

  1. Create a new console project in Visual Studio and Name it CSharpClass
  2. Right click on CSharpClass in the solution explorer and select add
  3. Select Class. Alternatively, you can press Shift + Alt + C
  4. You will be presented with a Add New Item dialogue window.
  5. Enter House.cs as the class name
  6. Click on Add button when you are done
  7. Double click on House.cs.

You will get teh following code

using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace CSharpClass
{
    class House
    {

    }
}

HERE,

class House

The keyword class defines a class House. For now our class doesn't do anything. Let's add some properties to it.

Class properties

Class properties also known as attributes, variable members etc. are variables that we define inside the class. Let's assume we are interested in the following properties of a house.

  • Number of Rooms
  • Type of House
  • Colour of the House

Just below the class definition, define the following variables.

private int numOfRooms;
private string houseType;
private string houseColor;

The above code defines one int variable and two string variables. These variables have global scope within the class but they are not accessible outside the class because we defined them as private. Remember, the class is the blueprint from which we will build our houses. The houses have different numbers of rooms, colour etc. So, how can we set the values of these variables outside the class?

C# Get Set

C# get and set methods allow us to retrieve and set class variable values respectively.

The simplicity form is as follows

public int numOfRooms { get; set; }
public string houseType { get; set; }
public string houseColor { get; set; }

HERE,

  • { get;} get is a keyword that automatically returns the value of the respective variable
  • { set;} set is a keyword that automatically sets the value of the respective variable

Its not mandatory to set both get and set methods. What if you are building a user class with a password property? You can allow setting the password for the user and not allow retrieving it. You can implement this as follows

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace CSharpClass
{
    class User
    {
        public string username {get; set;}
        public string password { set { password = value; } }
    }
}

HERE,

public string password { set { password = value; } } password property only defines the set method. Since we are only implementing a single method, we have included the body of set and assigned value to the property password. value is a built in keyword that holds the value that the user assigns the to class property.

If you try to access the password property using the following code,

User user = new User();

string pwd = user.password;

You will get the following error message.

The propert or indexer 'CSharpClass.User.password' cannot be used in this context because it lacks the get accessor

If you are working with constant values that you wouldn't want to change, then you can only implement the get method as follows

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace CSharpClass
{
    class DBConnect
    {
        public string server { get; set; }
        public string database { get; set; }
        public string user_name { get; set; }
        public string password { set { password = value; } }
        public string connection_string { get { return connection_string; } }
    }
}

Note: the connection_string property only has the get method. This is because we do not want anyone to change it outside the class.

Encapsulation

Encapsulation allows us to hide the implementation details and only expose methods that the users of the class will interact with. Let's we are designing a class for bank deposits. We wouldn't want to deposit a negative value. Another example would be a class that accepts days of the week. It wouldn't want input values that are not valid week days.

The following code shows how you can control the values that are assigned to class member variables.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace CSharpClass
{
    class Deposit
    {
        private string account_no;
        double deposit_amount;

        public string AccountNo
        {
            get
            {
                return this.account_no;
            }
            set
            {
                this.account_no = value;
            }

        }

        public double DepositAmount
        {
            get
            {
                return this.deposit_amount;
            }
            set
            {
                if (value <= 0)
                {
                    Console.WriteLine("Deposit amount should be greater than zero (0)");
                }
                else
                {
                    this.deposit_amount = value;
                }             
            }

        }
    }
}

HERE,

public double DepositAmount{...}
  • defines a public property that users can access. This public method is responsible for returning and assigning values to the private property deposit_amount. Note: we are using this keyword when accessing the variables. This is because these are instance variables and we want to make sure that the value set and returned is the one for the instance.

    set{ if (value <= 0) { Console.WriteLine("Deposit amount should be greater than zero (0)"); } else { this.deposit_amount = value; } }

The above allows us to check the passed in value for validation. If its less than or equal to zero (0), we write a validation message in the console window. If the value passes the validation test, we assign it to deposit_amount variable.

Class Constructor

A class constructor is the method that is executed when a class is initialized. Let's say you want to create an instance of the house class, you can pass in the parameters for the number of rooms, type of house and colour while you initialize the class.

A constructor is implemented as follows

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace CSharpClass
{
    class House
    {
        private int numOfRooms { get; set; }
        private string houseType { get; set; }
        private string houseColor { get; set; }

        public House(int no_of_rooms, string house_type, string house_color)
        {
            this.numOfRooms = no_of_rooms;
            this.houseType = house_type;
            this.houseColor = house_color;
        }
    }
}

HERE,

public House(int no_of_rooms, string house_type, string house_color)
{
    this.numOfRooms = no_of_rooms;
    this.houseType = house_type;
    this.houseColor = house_color;
}

The above constructor is a public method named House (same name as the class) that accepts three parameters. The passed in parameters are set to the class member variables during initialization. The constructor method can be used to initialize variables, set default values etc.

How to instantiate a class

Now that we have successfully created a house class. We can now build an actual house from our blueprint. The following code shows you how to do that.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace CSharpClass
{
    class Program
    {
        static void Main(string[] args)
        {
            //House house = new House();

            //house.houseColor = "Black";

            //User user = new User();

            //string pwd = user.password;

            //Deposit deposit = new Deposit();

            //deposit.AccountNo = "0001";
            //deposit.DepositAmount = 1;

            House house = new House(3, "Condor", "Gold");

            Console.WriteLine("Number of rooms: " + house.numOfRooms);
            Console.WriteLine("Type of house: " + house.houseType);
            Console.WriteLine("Colour of house: " + house.houseColor);

            Console.ReadLine();
        }
    }
}

Press F5 on the keyboard. You will get the following results.

Tutorial Image

Summary

  • A class is a blueprint that is used to build objects
  • A class can contain class member variables and methods
  • Get and Set methods are used to set values of class member variables
  • A class contructor is the method that is executed when a class is initialized.

Tutorial History

Tutorial version 1: Date Published 2015-07-24