Wednesday, March 31, 2021

What is Inheritance in C#?

Inheritance is a relationship between a base and its derived class. 

  • Base class
    • Also called the Parent class
    • This can be reusable by being inherited to the child classes
  • Derived class
    • The child class inheriting its parent
Advantages of using Inheritance
  • Provides resubility of existing implementation
  • Polymorphism, will see more on dedicated post that helps the same
Example,

class Vehicle
{
    public string make;
    
    public void StartEngine
    {
        //Different ways, its implementation
    }

}

class Car : Vehicle         //class Car Inherits from Parent class Vehicle
{
    public string model;
}

Now class Car has its own property model and it has also inherited the properties from Vehicle class as used Inheritance.

So creating intance of the class will allow you to use both as given below,

Car myCar = new Car();
myCar.make = "Mercedes";          //Inherited property
myCar.model = "C Class";            //Own property
myCar.StartEngine();                     //Inherited method


Sealed keyword in C# restrict the Inheritance of the class. 
Example,

sealed class Vehicle
{
    //implementation
}

class Car : Vehicle    //This is not allowed due to sealed keyword
{
    //
implementation

Will see more on scenario base queries on Sealed keyword dedicated topic. 

Abstract Classes
  • It is a half defined class, becuase it can have an abstract implementation and hence no instance can be created of abstract classes
  • This is helpful to create a base class to provide primary implementation to be followed for their child classes
  • All the abstract methods declaration requires its child classes do have an implementation of the same
  • Virtual Methods helps child classes to Override the same and change their own logic 
Interface
  • It's a contract 
  • classes that inherite the interface must have to implement all the methods from that Interface
  • Instance creation is not allowed
  • Helps to standardize coding practice across multiple classes
Hide base class member
  • if parent and child classes share the same name for their methods, the new modifier at method definition helps to hide the base class implementation

C# Properties (Getter & Setters)

Encapsulation can be achieved using C# properties. Encapsulation means hiding a complex object from the outer world, in other words not exposing sensitive information to the client. 

For which we will require Private members and as that is not accessible to the outer world we initialize the values using Properties. 

Basically, Property contains two methods Get and Set. 

Example,

class Car
{
        private string model;                //Field member

        public string Model                  //Property
        {
              get
                {
                        return model;        //Get method
                }
                set

                {
                        model = value;        //Set method
                }
        }
}

Achieving encapsulation,

  • Provides control for the class members
  • Making fields read-only (Only get method) and write-only (Only set method)
  • Provides data security

Tuesday, March 30, 2021

Access Modifiers - Encapsulation

We have seen Private, Public in our previous examples or posts. These are access modifiers now let's understand different types of Access Modifiers. 

Access Modifiers helps to achieve encapsulation,

Public             Accessible to all classes
Private           Only accessible to the same class
Protected       It is accessible within the same class and its inherited classes 
Internal           It is accessible within its own assembly, but not from other assembly

We will be going in details to upcoming topic of Inheritance where in broad level we can see the usage of given access modifiers

Class Car
{
        private string color; 
        public string make";
}

Class Program
{
    static void Main(string[] args)
    {
            Car myCar = new Car();
            myCar.color = "Red";      //This will throw error of inaccesible due to its protection level
            myCar.make = "Audi";    //This is allowed
    }
}

Encapsulation can be achieved through modifiers, means you can hide sensitive information from clients. 

What is Constructor?

Constructor is used to initializing the Class and Private members within the class. 

It is like a method but with no return type like void or int or any. Constructors are the first being called.


For example,

Class Car
{
        private string color; //Private field member


        public Car(string _color)    //Constructor initialization
        {
                color = _color;
        }

}


//Initializing Class

Car myCar = new Car("Red"); // This will call the constructor 

Basic things to remember,

  • It must match the class name
  • No return type is allowed
  • No separate method call required, as above example at class initialization it is called directly
  • All classes have their own default constructors if it is not declared.
  • Constructors can have multiple parameters and such is called Parameterized Constructors
  • Constructors can be overloaded by using different parameters (Will see more on Overloading and Overriding in upcoming posts)
Types of Constructors

  • Parameterless Constructor / Default Constructor
    • If no constructor is defined C# create for itself
  • Parameterized Constructor
    • Constructor with parameters one or many is called parameterized constructor
    • Used to initialize the members of the class
  • Static Constructor
    • Static constructor used to initialize the static members
    • You can have Public and Static constructor
  • Private Constructor
    • If a class has a Private Constructor only, other classes will not be able to create an instance of that class 

Monday, March 29, 2021

Class Members

 Class is a combination of its Fields and Methods and that is referred to Class Members

Class Car
{
        String Color;
        String Power;     

        Void Speed()
        {
            //Method Definition to calculate Max speed based on it's specifications
        }

}

Class Car consist of its member Color and Power and Speed() is a method. You can utilize the same object as many times as you need following the program need. Below is how you can create an object and initialize its members to required specification.

Car carObject = new Car(); //Creating Object of Class Car
carObject.Color = "Blue"; //Initializing fields
carObject.Power = 1000; //Initializing fields
carObject.Speed(); //Method Calling

There are acess modifiers used to restrict the usage of Class members, we will see it in upcoming post. Please stay connected. 

Working with Classes and Objects

I would request you to review my previous blog post for a basic understanding of Object Oriented Programming (To Read Click Me)

From the previous post, we will extend our Car example for better realistic understanding,

  • Class Car contains attributes such as color, engine power, size, airbag
  • Class Car contains methods such as drive, brake

Classes are just a blueprint. Objects are inherited property of the blueprint and it's reusable in nature.

Class example,

Class Car
{
        String Color;
        String Power;     

}

        From the above example, we have declared a class named Car and attributes are Color and Power. 

Creating an Object from the above class

Car carObject = new Car();

        Now, you can create as many as the object you want depending on the need of the program. This is called reusability. The below example explains the same.

        Car audi = new Car();
        
Car ferrari = new Car();


What is OOP (Object Oriented Programming)?

Object-Oriented Programming is about creating Objects out of Classes


What is a Class?

Class is nothing but a blue print or a template for an object. It contains the attributes and methods.

For example, Car is a class and Audi, Mercedes, Porche, Farrari are objects of it. 

What is an Object?

           An instantiation of the class creates and an Object. This helps to reduce the repetition of code.

For example, from above one Audi is an object created from a abstract Car class. 

Pillars of Object-Oriented Programming

  • Encapsulation

    • This means show only necessary to the outer world, achieved through Access Modifiers

  • Inheritance

    • Inheriting properties from a parent object makes it more reusable and extensible
    • Helps to remove redundant code

  • Polymorphism

    • Same method signature with various forms or taste
    • Dynamic Polymorphism
    • Static Polymorphism

  • Abstraction

    • This helps to hide the complexity in your code
    • Abstract classes and methods help to achieve multiple forms and are reusable in nature

Advantages of Object-Oriented Programming

  •  Reduce repetition of code
  •  Clear Code, Less Code
  •  Faster and manageable
  •  Easy to maintain, modify and debug
  •  Provides reusable application framework
  •  Rapid development

Do you have any questions? I would be glad to answer and help or make a dedicated post.

C# Interview Prep: 100 Common Questions for 0-3 Years Experience

Common C# Interview Questions  Basics of C# Language: What is C#? C# (pronounced C sharp) is a modern, object-oriented programming language...