Objects and Classes in C#

Tutorials PanelPosted by

In this lesson, you will learn how to create classes and their properties, methods, events. Also, you will learn how to set up the access level for a class and its members, as well as learning other object-oriented concept, such as Encapsulation, constructors, and destructors.

What is a class in C#?

In object-oriented programming, a class is an entity that you create to enable you to have your own custom type of object that can be used across the project. The class can have properties, events, methods. An instance of a class can be created and assigned values to its properties from anywhere in the code (static class can’t have an instance).

A design of new entity starts with a blueprint. The class is the blueprint of an object. The object can be anything: a person, a car, a building, or an animal. The object, or class, can have properties, such as name, color, height, etc…

Properties can be assigned values, example:

My car color is “Red”, the person height is “5.9”

Class example in C#:

        public class Car
        {
            private string _make;
            private string _color;
            private string _year;
            public string Make
            {
                get { return _make; }
                set { _make = value; }
            }
            public string Color
            {
                get { return _color; }
                set { _color = value; }
            }
            public string Year
            {
                get { return _year; }
                set { _year = value; }
            }
            public void TurnEngineOn()
            {
                Console.WriteLine("My " + Color + " " + Make + " engine is on");

            }
            public void TurnEngineOff()
            {
                Console.WriteLine("My " + Color + " " + Make + " engine is off");

            }
        }

The above is a class “Car” that has the properties Make, Color, and Year. The class contains two function, TurnEngineOn(), and TurnEngineOff().

Now let’s create an instance of this class.

        static void Main(string[] args)
        {
            // Create an instance of the class
            Car MyCar = new Car();
            // Set the properties of the class
            MyCar.Make = "BMW";
            MyCar.Color = "Red";
            MyCar.Year = "2015";
            // Call a function of that class
            MyCar.TurnEngineOn();
            Console.ReadKey();
        }

Output

c# class

We will explain more about properties, access identifier later on in this lesson.

Access modifier in C#

Access modifiers are used to define a visibility of a class, property, method, or struct. A modifier is very important in object-oriented programming and needs to be taken seriously. Not all the class members need to be visible to the client outside the project or eth assembly. Below is a brief explanation with example about the available access modifier in C#.

Private

The private access modifier can be used for a property, variable, or method. This modifier makes those members private and invisible to programs outside the class assembly.

Example of private modifier in C#

  private string _make;

The above is to be used solely for internal class operations. No other programs or classes can access this variable.

Public

Public modifier is used to set visibility to properties and methods to “True”. In the above “Car” Class, the properties Make, Year, and color are public, thus the ability of using when we created an instant of this class in the main program.

Example of public modifier in C#

public string Make
{
get { return _make; }
set { _make = value; }
}

Protected

Protected identified can be used   for a property, variable, or method. When this identifier is used, it set the visibility for those members to “true” only for the class that inherits from the main class. we will discuss more about inheritance in incoming lessons.

Example of protected modifier in C#

Protected String _FirstName;

C# fields

Fields are variable that can be declared in a class (or struct) and are used to give value to a property. They also can read value from a property.

Example of fields in C#

The class “Car” contains 3 fields:

private string _make;
private string _color;
private string _year;

Those fields are only used to set and get value operations for the properties. Their cant be accessed from outside the class due to the “Private” keyword. We will discuss later in this lesson the importance of keeping those fields private and the properties public.

C# Properties

Unlike fields, properties are assessable form outside the class, so the instance of that class can have values assigned to its properties, as well as reading value from them. This doesn’t mean that fields can’t be public and properties can’t be private. However, in programming, generally the purpose of a property is to be visible form other areas in the program so a value can be assigned or read. Fields tends to remains private as their role is for internal class operation only.

Properties are members or a class, struct, or interface. They have accessor to read and write their values.

Example of properties in C#

public string Year
{
//Get the value 
get { return _year; }
// Set the value
set { _year = value; }
}

The property Year gets and sets its value from the fields _year. Year is public, while _year is private and only accessible within the class.

The “set” and “get” keywords are called accessors.

Encapsulation

The word encapsulation comes from “capsule”, and it means to keep some of the class members private to other classes and programs. The hiding of the fields in the class “Car” is a perfect example of encapsulation. It’s always safe to keep some of the information hidden from outside the class.

Methods can be encapsulated as well; for example, the “Car” class can define methods that re only to be used inside that class. Example:

public class Car
        {
            // define the field _mileage
            private int _mileage;
            // define the property Mileage
            public int Mileage
            {
                get { return _mileage; }
                set { _mileage = value; }
            }
            // define a function to convert mile to KM.
            // Note that the function is encapsulated by the 'private' keyword.
            // The only purpose of this function is to be used within the class
            private double calculateKilometrage(int mileage)
            {
                double result;
                result = mileage / 0.62137;
                return result;
            }
            // degfine a function to show the mileage and kilometrage
            // the function calculateKilometrage is used inside the function below and again cant be assessed from outside the class.
            public void ShowMilage()
            {
                Console.WriteLine("The mileage is: " + Mileage);
                Console.WriteLine("the kilometrage is: " + calculateKilometrage(Mileage).ToString("00.00"));
            }
        }

        //Now create an instance of this class and call the function ShowMilage()
        static void Main(string[] args)
        {
            // Create an instance of the class
            Car MyCar = new Car();
            // Set the properties of the class
            MyCar.Mileage = 50000;
            // Call a function of that class
            MyCar.ShowMilage();
            Console.ReadKey();
        }

Output

c# class

As you see in the example above, the function calculateKilometrage() is encapsulated to be only used in class so it can’t be accessed from outside. The beauty of encapsulation is it gives you the ability to hide the function that is not useful outside the class.

What is a constructor?

Constructors are special methods that get invoked automatically when a instance of a class is created. The “new” operator is what invokes the constructor. In C#, there are 5 types of constructors:

  1. Default Constructor
  2. Parametrized Constructor
  3. Copy Constructor
  4. Static Constructor
  5. Private Constructor

Default constructor

If a class doesn’t have a constructor, the compiler will generate a constructor that has no parameters. You still can provide a constructor with no parameter, which will be treated by the compiler as default, which is same as not having a constructor at all.

Example of default constructor

        public Class Car
        { } // class with no constructor will have a default constructor when initiated.

        public class Car
        {
            public Car() { } // default constructor
        }

Both of the class above will result in invoking het default constructor when creating an instance. Keep in mind that default constructor doesn’t not have parameters.

Now let’s create an instance of that class

Car _myCar = new Car();

Parameterized constructor

Any constructor that has at least on parameter is called parameterized constructor. The use of parameters when creating an instance of a class is to assigned values to variables which will be used in that class.

Example of parameterized constructor

        public class car
        {
            // Create a parameterized constructor which takes 2 parameters.
            public car(string brand, string color)
            {
                // assign parameters value to local variable
                string _myBrand = brand;
                string _mycolor = color;

            }
        }

Now let’s create an instance of the class Car

car  myCar = new car("BMW", "Black"); // passing values to the class

Copy constructor

A copy constructor is a constructor that takes previously initiated instance of the same class being initialized.

Example of copy constructor

 public string Brand { get; set; }
        public string Color { get; set; }



        public car(string brand, string color)

        {
            Brand = brand;
            Color = color;


        }


        public Car(Car otherCar)
        {
            Brand otherCar.Brand;
            string Color = otherCar.Color;

        }

Static constructors

In C#, a static constructor is used to initialize static fields in a class. It’s also used to perform an action that will be performed only once, such as creating a singleton class.

The static constrictor is invoked when a static member is referenced or an instance of a singleton class is created.

Example of Static constructor

 public class Car3
        {
            public string Brand;
            public string Color;
            public static int NumberofTires;
            public Car3(string brand, string color)
            {
                brand = Brand;
                color = Color;
            }
            static Car3()
            {
                NumberofTires = 4;
            }
        }

Private Constructor

Private constructor is used when you want the class to remain private, which can’t be inherited nor initiated. However, we can create a static method or property in order to access the method or property of that class.

Example of private constructor

 public class Car
        {
            private Car()
            {
                //Private Constructor
            }
            public static int NumberOfTires()
            {
                return 4;
            }
            public static string getNumberOfTires()
            {
                return "Number of tires in a car is " + NumberOfTires.ToString();
            }
        }

Now let’s use this class from a static method

static void Main(string[] args)
{
Car.currentCount = 4;
Car.getNumberOfTires();
Console.WriteLine(Car.getNumberOfTires().ToString());
}
 

 

 

Leave a Reply