C# class

A class is used to model an object, it defines what the object is and how it is going to behave. A class is like a blueprint, from a single class we can create as many objects as we want at runtime, creating an object from a class is called instantiation. A class is a reference type meaning that when an object of the class is instantiated and the instantiated object is assigned to some variable, the variable which the instantiated object is assigned to holds only the memory location of the instantiated object. If the instantiated object is assigned to multiple variables, all the variable refers to the memory address of the instantiated object, changes made to one variable are reflected in the other variables.
When you declare a variable of a class type without instantiation, the created variable holds a null value until you assign to it an object that is compatible with it.
eg.


SomeClass someclass; // someclass is a variable of type SomeClass and it has a value of null

SomeClass someclass2 = new SomeClass() // someclass2 is a variable of type SomeClass and 
                                       //its value is located in the managed heap.




If we define a class called Person, we know that a person can be a male or female, a person can have an occupation being a student, engineer, business owner or a medical doctor. We can instantiate an object of the person class as a teacher, engineer or a doctor from the person class.

A person class


We can create as many objects as we want from the person class.


The above class models a person class with only properties, we use functions inside a class to define what the object of the class can do, for example, we can upgrade our person class to have the capability to do something, i.e drink, eat, walk, etc.

The code below defines a person class with only properties with no constructor, the type of properties we defined here is called auto-implemented property, auto-implemented properties are used when no additional logic is required in the set and get accessors of the property



    class Person
    {  
        public string Name { get; set; }
        public int Age  { get; set; }
        public PersonGender Gender { get; set; }
        public string Occupation { get; set; }

    }


We can create an instance of the class like this.


     
    Person person = new Person();
    person.Name = "Anas Abubakar";
    person.Age = 22;
    person.Occupation = "engineer";
    person.Gender = PersonGender.Male;

    Console.WriteLine( $"Name:{person.Name}"  + " \n" + $"Age:{person.Age} " +

        "\n" +  $"Occupation:{person.Occupation}" + " \n" + $"Gender:{ person.Gender} ");


We can also instantiate and initialize the person class this way.


   Person person = new Person
   {
     Name = "Anas Abubakar",
     Age = 22,
     Occupation = "Engineer",
     Gender = PersonGender.Male
     };


The above method of instatiation and initialisation of a class is called object initializer. Object initializer lets you initialize the accessible fields and properties of a class without calling the class's constructor. Even though we didnt define constructor for the person class the C# compiler created one for us, the type of constructor created by the C# compiler is called default constructor.

Lets recreate a person class this time with a constructor and fields.


 
    class Person
    {
        public Person(string name , int age, PersonGender gender, string occupation)
        {
            Name = name;
            Age = age;
            Gender = gender;
            Occupation = occupation;
        }

        public string Name;
        public int Age;
        public PersonGender Gender;
        public string Occupation;

    }




Note that in the above code we replaced the properties with fields, and we added a constructor to the class, in order to instantiate the class we must initialize the fields because we explicitly provide a constructor to the class. Constructor is called every time an object of a class is created, constructors have the same name as the class, they are mostly declared with a public access modifier. If we want to instantiate the class without initializing the fields of the class we have to explicitly provide an empty constructor.



 
    class Person
    {
        public Person(string name , int age, PersonGender gender, string occupation)
        {
            Name = name;
            Age = age;
            Gender = gender;
            Occupation = occupation;
        }

        public string Name;
        public int Age;
        public PersonGender Gender;
        public string Occupation;

    }


// we consume our class this way

    public enum PersonGender
    {
        Male,
        Female
    }

    class Program
    {

        static void Main(string[] args)
        {

            Person person = new Person("Anas", 22, PersonGender.Male, "Engineer");

            Console.WriteLine($"Name:{person.Name}" + " \n" + $"Age:{person.Age} " +
             "\n" + $"Occupation:{person.Occupation}" + " \n" + $"Gender:{ person.Gender} ");
        }
    }


We cannot instantiate the person class with an empty constructor if we want to do that we have to explicitly add an empty constructor to the person class.


 
    class Person
    {
       
        public Person()
        {

        }

        public Person(string name, int age, PersonGender gender, string occupation)
        {
            Name = name;
            Age = age;
            Gender = gender;
            Occupation = occupation;
        }

        public string Name;
        public int Age;
        public PersonGender Gender;
        public string Occupation;

    }

    
    public enum PersonGender
    {
        Male,
        Female
    }

    class Program
    {

        static void Main(string[] args)
        {

            Person person = new Person();

            Console.WriteLine($"Name:{person.Name}" + " \n" + $"Age:{person.Age} " +
             "\n" + $"Occupation:{person.Occupation}" + " \n" + $"Gender:{ person.Gender} ");
        }
    }
Empty constructor serves as a default constructor for a class, if we did not supply anything to the constructor, the default constructor initialized the class's fields/properties to their default value. eg integer, float, double are initialized to zero, any reference type is initialized to null, bool is initialized to false.

Static class

If we add a static keyword to a  class member, the member can be accessed without creating an object of the class. We can access the static member via the class name eg



as shown in the above picture only the fields that are declared as a static field can be accessed via the class name.


    class Person
    {     
        public Person() {}

        public Person(string name, int age, PersonGender gender, string occupation)
        {
            Name = name;
            Age = age;
            Gender = gender;
            Occupation = occupation;
        }
        public static string Name; // static member
        public int Age;
        public PersonGender Gender;
        public string Occupation;

    }



// Note that before printing the fields of the class to the console we accessed the Name field via the class's name without creating an object of the class and assigned a "Hello" to it.


    public enum PersonGender
    {
        Male,
        Female
    }

    class Program
    {

        static void Main(string[] args)
        {

            Person person = new Person();

            Person.Name = "Hello";

            Console.WriteLine($"Name:{Person.Name}" + " \n" + $"Age:{person.Age} " +
             "\n" + $"Occupation:{person.Occupation}" + " \n" + $"Gender:{ person.Gender} ");
        }
    }

If you declare a class as a static class you cannot instantiate an object of the class, static classes have no constructor, static class remains in memory for the lifetime of the application, static class can only contain static members( methods and fields) and const fields. A static class is usually used as a container for methods and constant fields. A static field can only contain static or constant fields, you cannot declare a  static const field. example.


The above picture shows part of the  .NET Math class, note that the only two const fields belonging to the Math class are declared const with no static keyword because you cannot declare a constant field as static.


Class inheritance

Inheritance allows us to create one or more specialized classes from a single class, the derived class can reuse or modify the base class's methods and properties. By declaring a base class method as virtual we allow any class that inherits the class to override the method with its own implementation. if we declare a member method as abstract the derived class must override the method provided the derived class is a concrete class.
in C# a class can inherit only from one class, however, a class can inherit from multiple interfaces.
If we remove an occupation field from our person class we can create many specialized person classes like a student class derived from person class.



 
    class Person
    {
        public Person(string name , int age, PersonGender gender, string occupation)
        {
            Name = name;
            Age = age;
            Gender = gender;
          
        }

        public string Name;
        public int Age;
        public PersonGender Gender;
     
    }


   class Student:Person
    {
     
     public string[] courses;
     public float[] grades;
       

    }


    class Teacher:Person
    {
     public string course_he_teach;
     public decimal salary;

     }


In the example below, we created two classes that inherit from a Person class, note that in the constructor of Student and Teacher class we initialized the name, age and gender field by calling the base constructor(constructor of the base class).


    class Person
    {
        public Person() { }

        public Person(string name, int age, PersonGender gender)
        {
            Name = name;
            Age = age;
            Gender = gender;
      
        }
        public string Name;
        public int Age;
        public PersonGender Gender;
      

    }

    class Student : Person
    {
        public Student(string name, int age, PersonGender gender,
                        string[] courses, float[] grades) : base(name, age, gender)
        {
            this.courses = courses;
            this.grades = grades;
        }
        public string[] courses;
        public float[] grades;
    }

    class Teacher : Person
    { 
        public  Teacher(string name, int age, PersonGender gender,
                         string course, decimal salary):base(name,age, gender)
        {
            this.course = course;
            this.salary = salary;
        }
        public string course;
        public decimal salary = 0.0m;
    }

     public enum PersonGender
    {
        Male,
        Female
    }

    class Program
    {

        static void Main(string[] args)
        {

            string[] courses = { "Mathmatics", "Physics" };
            float[] grades = { 77, 63 };

       

            List<Teacher> teachers = new List<Teacher>();
            Student student = new Student("Omar hassan", 22, PersonGender.Male,courses, grades);

            Teacher maths_teacher = new Teacher("James Harold", 35, PersonGender.Male,
                                                  "Mathematics", 55_000);

            Teacher physics_teacher = new Teacher("Helena Micheal", 45, PersonGender.Female,
                                                     "physics", 65_000);


            teachers.Add(maths_teacher);
            teachers.Add(physics_teacher);
            
            
            Console.WriteLine($"Name:{student.Name}" + " \n" + $"Age:{student.Age} " +
            " \n" + $"Gender:{ student.Gender} " +
            "\n \n" + "Student's courses and grades:" );

            for (int i = 0; i < courses.Length; i++)
            {
                Console.Write(courses[i] + " " );
                Console.WriteLine(grades[i]);

            }

            Console.WriteLine(" \n teachers that taught the courses:");

            for (int i = 0; i < courses.Length; i++)
            {
                Console.WriteLine( teachers[i].course + " " +  teachers[i].Name );


            }
        }
    } 

Abstact class

An abstract class is a class with an abstract modifier keyword in front of it, an abtract class cannot be instantiated.We declare a class as an abstract when we want a class to be used only as a base class, an abstract class may contain abstract methods or properties.Abstract method are declared by putting the abstract keyword modifier infront of the method.Abstract methods does not have a body, any derived class must implement all the abstract methods. Only non abtract class can implement an abtract class.abstract methods cannot be declare in a non abtract class, only abstract class can contain an abtract class memeber, an override keword is used by a derived class to provide an implementation for the abstract method. Note that a sealed modifier cannot be used in defining an abtract class.
Consider the code below.


  abstract class Shape
{
public abstract double CalculateArea();
} class Square : Shape
{
int side; public Square(int side )
{
this.side = side;
}
// GetArea method is required to avoid a compile-time error.
public override double CalculateArea() => side * side;
} class Triangle : Shape
{
int width, height; public Triangle(int width, int height)
{
this.width = width;
this.height = height;
}
// GetArea method is required to avoid a compile-time error.
public override double CalculateArea() => (width * height) / 2;
} class Circle : Shape
{
int radius; public Circle(int radius)
{
this.radius = radius;
}
// GetArea method is required to avoid a compile-time error.
public override double CalculateArea() => Math.PI * Math.Pow(radius,2);
} class AbstractClassDemo
{ static void Main()
{
var square = new Square(12);
var circle = new Circle(3);
var triangle = new Triangle(6,8); Console.WriteLine($"Area of the square = {square.CalculateArea()} \n" +
$"Area of the circle = {circle.CalculateArea()} \n" +
$"Area of the circle = {triangle.CalculateArea()}");
} }

in the above code a class shape is declared abstract since shape is a generic term, there is noway to create a shape concrete object, if we talk about shape we have to specify which type of shape,circle, square, hexagon etc, thus we create the shape class as abstract since it doesnt make sense to instantiate a shape class. In every concrete implementation we override the CalculateArea() method to provide the relevant impelemtation for each shape sub class.

Comments

  1. Best Article on Class explanation on internet, never seen before

    ReplyDelete

Post a Comment

Popular posts from this blog

C# Interface