Types of variables in c#

value and reference type             The c# support two major variable types, they are “Value type and Reference type”. Int, Float, Decimal , Char , etc are the value types and Classes, , Delegates , Interfaces , Arrays , etc are the Reference types.

Now we have seen c# has two different types of variable types. These types must have some difference so lets see how this value and reference type differs.

Value type and Reference type

I hope everyone knows, when ever we initialize a variable there is a memory allocation will happens, we should know this to know about the difference of value and reference types.

Value type

  • Value type variable store data directly into the memory location.
  • If we get any copy of the data to another variable and try to change any variable data , the changed data will affect only to the variable we try to change , other variable remain the old value.
  • Value type data will be saved in Stack memory.

Reference type

  • Reference type variable does not save data directly to the memory location. it stores the reference of the actual data.
  • If we get any copy of the data to another variable and try to change any variable data , the changed data affect every copy of the object.
  • Reference type data will be saved in Heap memory

Example

using System;

class RefClass
{
    public int Value = 0;
}

class TestProgram
{

static void Main() {

    int valtype1 = 0;
    int valtype2 = valtype1;
    valtype2 = 999;
    RefClass refObj1 = new RefClass();
    RefClass refObj2 = refObj1;
    refObj2.Value = 999;
    Console.WriteLine("Value type values: {0}, {1}", valtype1, valtype2);
    Console.WriteLine("Reference type values: {0}, {1}", refObj1.Value, refObj2.Value);
}

}

 

Output

Values: 0, 999
Refs: 999, 999

Value type

check the above example valtype2 is assigned from the variable valtype1 and changing the data valtype2. but in the output the change has been reflected only to the changed variable.

Reference type

check the above example refObj2 is assigned from the object refObj1 and changing the data inside the object refObj2. The change we made was in refObj2 but in the out put the change applied in the refObj2 reflected refObj1.

Interface in OOPS

Introduction

Interface is introduced to achieve multiple inheritance. Multiple classes cannot be inherited in C#, because classes have definitions for members, so the compiler will get confused with members which to invoke.

Ex:

    public class A
    {
        public int Add(double a, double b)
        {
            return System.Convert.ToInt32(a + b);
        }
    }
    public class B
    {
        public int Add(double a, double b)
        {
            int x = System.Convert.ToInt32(a);
            int y = System.Convert.ToInt32(b);
            return x + y;
        }
    }
    public class C : A, B
    {
        // not possible in C#.
    }
    public class D
    {
        public void main()
        {
            A a = new A();
            B b = new B();
            C c = new C();

            // will return 12 (5.55+6.55=12.10, So while converting .10 will be ejected bcz less than .50)
            int x = a.Add(5.55, 6.55);

            // will return 13(5.55 will be taken as 6 bcz .55 is greater than .50 also 6.55 will be taken as 7 So 6 + 7 = 13) not possible in C#
            int y = b.Add(5.55, 6.55);

            // in this case the compiler cannot take Decision on which method to invoke, because Both A and B have Add and function differently.
            int z = c.Add(5.55, 6.55);
        }
    }

To avoid such situations, interface is used. In interface members does not have definition, the must have methods and properties can be declared. So the inheriting class can define the member as required. As in class the default Access modifier for the interface is internal. But the default Access modifier of the interface member is not like in class. In interface. The default Access modifier is PUBLIC, but in class it is PRIVATE.Interface

Implicit Implementation

    interface iA // internal interface
    {
        int Add(double a, double b); // public method.
    }
    interface iB
    {
        int Add(double a, double b);
    }
    class C : iA, iB
    {
        public int Add(double a, double b)
        {
            return System.Convert.ToInt32(a + b);
        }
    }

This is implicit implementation of interfaces. Even if both interfaces have “Add” method, single method definition will satisfy both interfaces.

    class D
    {
        void main()
        {
            iA ia = new C();
            // will point to “Add” method in class C.
            ia.Add(5.55, 6.55);

            iB ib = new C();
            // will point to “Add” method in class C.
            ib.Add(5.55, 6.55);

            C c = new C();
            // will point to “Add” method in class C.
            c.Add(5.55, 6.55);
        }
    }

So there is no confusion about pointing method.

Explicit Implementation

Even if you need to implement each interface method separately, it can be done by explicit implementation. But explicitly implemented method cannot be invoked directly from derived class. Because we cannot specify any access modifiers for explicitly implemented methods. It will be private by default. It can be either accessed by.

  1. Another method in derived class
  2. Creating object for interface type.
ANOTHER METHOD IN DERIVED CLASS
    interface iA // internal interface
    {
        int Add(double a, double b); // public method.
    }

    interface iB
    {
        int Add(double a, double b);
    }
    class C : iA, iB
    {
        // Explicit implementation of “iA” interface method
        int iA.Add(double a, double b)
        {
            return System.Convert.ToInt32(a + b);
        }
        // Explicit implementation of “iB” interface method
        int iB.Add(double a, double b)
        {
            int x = System.Convert.ToInt32(a);
            int y = System.Convert.ToInt32(b);
            return x + y;
        }
        // Exposing “iA” interface method through another public method
        public int AddBeforeConverting(double a, double b)
        {
            iA ia = this;
            return ia.Add(a, b);
        }

        // Exposing “iB” interface method through another public method
        public int AddAfterConvertion(double a, double b)
        {
            iB ib = this;
            return ib.Add(a, b);
        }
    }

Here we use different method names, so no confusion.

CREATING OBJECT FOR INTERFACE TYPE
    interface iA // internal interface
    {
        int Add(double a, double b); // public method.
    }

    interface iB
    {
        int Add(double a, double b);
    }
    class C : iA, iB
    {
        // Explicit implementation of “iA” interface method
        int iA.Add(double a, double b)
        {
            return System.Convert.ToInt32(a + b);
        }
        // Explicit implementation of “iB” interface method
        int iB.Add(double a, double b)
        {
            int x = System.Convert.ToInt32(a);
            int y = System.Convert.ToInt32(b);
            return x + y;
        }
    }
    class D
    {
        void main()
        {
            iA ia = new C();
            // will return 12 as it convert after addition
            ia.Add(5.55, 6.55);

            iB ib = new C();
            // will return 13 as it convert numbers before addition
            ib.Add(5.55, 6.55);

            C c = new C();
            // Cannot use like it, method won’t be available in the object.
            c.Add(5.55, 6.55);
        }
    }

Interface

  • Interface is defined with the keyword “interface”.
  • Interfaces are used in design level.
  • Object for interface cannot be created directly. But it can be created by calling derived class constructor(as did with abstract class).
  • Interfaces only can have declaration, but not definition

Ex:

Public interface iA
{
    String Father; // field is not allowed in interface
    String Name{get;set;} // property is allowed in interface
    Int Add(int a, int b);
}
  • Member fields cannot be used in interface.
  • Access modifiers cannot be used with interface members.
  • All the interface members must be implemented in the derived classes.

After reading Abstract class and Interface, most of the people will have a confusion on why we have both abstract class and interface, and where to use them, because both have many similar features. It has specific reasons to have both together.

  • When we have a normal base class to inherit, then we cannot inherit another abstract class too.
    class A
    {
        private string _name;
        public string GetName()
        {
            return _name;
        }
    }
    abstract class B
    {
        public abstract void SetName(string Name);
    }

    interface iC
    {
        void SetName(string Name);
    }
    class D : A, B
    {
        // This is not possible, because multiple inheritance on class is Not possible in C#
            }
    class D : A, iC
    {
        //This is possible. Here only one class is inherited and another one is interface
    }

In the above situation we need to use interface instead of abstract class.

  • When we are in need of some method declarations and some methods with method definition, then we have only one choice of Abstract class.(some function in a fixed manner and some function according to the consumer requirement on implementation).

There may be more reasons, so please refer the internet also. As said above, the abstract class and interface are used in the design level. So it is mostly used in design patterns.(if you wish to learn more about design patterns, can refer to internet) For more references about OOPS: MSDN – OOPS(C#)

Refer for more OOPS Concepts

Abstract classes in OOPS

Abstract Classes

  • Abstract classes are defined with the keyword ‘abstract’.
  • They are used in design level.
  • Object cannot be created to abstract classes directly. But object can be created to type of abstract class by calling derived class constructor
Abstract Class
Every animal have its specific type just like Wolf, Gold Fish, Dog etc. So assume as No object for Animal class, but inheriting Animal class to any other type of animal we can get the base behavior of animal in those type of animals.

Ex:

        abstract class A
        {
            public abstract int Add(int a, int b);
        }

        class B : A
        {
            public override int Add(int a, int b)
            {
                return a + b;
            }
        }

        class C
        {
            public C()
            {
                A a = new A();  // it is not possible, because there is no constructor for abstract class.
                A a = new B();  // This is possible, because B is not abstract class, so It has it’s default constructor.
                a.Add(10, 20);  // will return 30.
            }
        }
  • Abstract classes can have abstract methods and properties as well as non abstract members. But a normal class cannot contain abstract members.
  • An abstract member should be implemented in its derived classes.
  • An abstract method or property will not be having it’s definition/implementation in abstract class.
  • It is not mandatory to have at least single abstract member in an abstract class. We can have defined methods only in an abstract class.

Ex:

        public abstract class A
        {
            public string Add(string a, string b)
            {
                return a+b; // A normal method
            }
            public static int Add(int x, int y, int z)
            {
                return x + y + z;
            }
        }

Abstract class can have a normal method, but it cannot be used without inheritance. Because object cannot be created for abstract class. At the same time a static method can be used in abstract class and it can be used without inheritance. Because static members doesn’t need object to invoke.

From the above example, “public string Add(string a, string b)” method need inheritance to be invoked at the same time “Public static int Add(int x, int y, int z)” method can be used directly with class name

Ex:

        public abstract class A
        {
            // Abstract property.
            public abstract string FirstName { get; set; }
            // Abstract method.
            public abstract int Add(int a, int b);
            public string Add(string a, string b)
            {
                return a + b; // A normal method
            }
            public static int Add(int x, int y, int z)
            {
                return x + y + z;
            }
        }

        public class B : A
        {
            private string _FirstName;
            public override string FirstName
            {
                get { return _FirstName; }
                set { _FirstName = value; }
            }
            public override int Add(int a, int b)
            {
                return a + b;
            }
        }
        public class C
        {
            public C()
            {
                A b = new B();

                b.Add("Mathew ", "Markose"); //will return “Mathew Markose” as result
                A.Add(10, 20, 30); // will return 60 as result
            }
        }

Refer for more OOPS Concepts

Access Modifiers in C#

Access Modifiers / Access Specifiers are keywords used in object oriented programming to restrict access to classes or class members like methods and variables. It is a part of programming syntax to achieve the encapsulation of components. There are different kinds of Access Modifiers with different kind of behaviors. Access Modifiers in C# are

  • Public
  • Private
  • Internal
  • Protected
  • Protected Internal
  • Sealed

Public

It can be accessed from anywhere as object or for inheritance. In C# public is default for interfaces

Private

It is only accessible inside the same class. When an object of the class is created, private methods and variables won’t be accessible. In the case of inheritance, private properties and methods are inherited, but won’t be accessible. Nothing can be created as private direct under namespace. Which means a class direct under namespace cannot be given private modifier. Only nested class can be assigned as private. In C# private is default for class members.

Internal

This is just like public, but scope only inside the assembly. Outside the assembly, It won’t be available for inheritance as well as for object. In C#, internal is default for a class direct under namespace.

Protected

It is only available for inheritance, will not be accessible from object of the class. Which means, a protected member can be used only inside the child class not directly from parent class. Scope for inheritance is anywhere:- accessible from outside of the assembly also possible. A class direct under namespace cannot be created as protected.

Protected Internal

This is the union of Protected and Internal. It can be accessed from object only inside the assembly, but accessible for inheritance globally. As protected, no element direct under namespace can be created as protected internal.

Sealed

Sealed modifier is used to protect the class or class member from being inherited. A class with sealed modifier cannot be inherited, but it can inherit another class. But in case of class members, it can only be used to overridden members. Which means a new member cannot be create as sealed. So it protect class members fro multi level inheritance.

    class A
    {
        String name;
    }
    sealed class B : A
    {
        int Age; //this is possible B can inherit A
    }
    class C : B
    {
        DateTime DOB;   // This will return error on compile time, bcz, sealed class B cannot be inherited.
    }

Summary

Refer for more OOPS Concepts

What is Encapsulation in OOPS?

Encapsulation is the process of wrapping method and attributes into single unit and hiding unnecessary data by using access modifiers.

public class A
{
    Private int Id;
    Private string _Name;
    Public string Name
    { 
        get { return _Name;}
        set{_Name = value;}
    }
    Public void SaveandPrint()
    {
        Save();
        Print();
    }
    Private void Save()
    {
        // Call the ADO.Net method to save data
    }
    Private void Print()
    {
        // create the object of report and print data
    }
}

Here the object expose only the information of SaveandPrint(). But internally it is split into two methods as Save() & Print() and it is not exposed to end user. Also it wrap the variable and function into single unit called class. While creating object also it keep in a single unit.

What is Abstraction in OOPS?

The meaning of abstract is existing in thoughts or as idea but not having a physical or concrete existence. It’s mainly used in design level. Abstract classes and interfaces are best examples for abstraction. We can specify the abstract actions which does not have an implementation in the same class but in the derived class.

public abstract class A
{
    Public abstract int Add(int a, int b);
}
Public class B : A 
{
    Public override int Add(int a, int b)
    { 
        Return a+b;
    }
}

What is Polymorphism in OOPS?

Polymorphism is a Greek word which means many-forms. That means look same but act different. There are two types of polymorphism in .Net

  • Static Polymorphism
  • Dynamic Polymorphism

Static Polymorphism

Method overloading and Operator overloading are static polymorphisms. Method overloading is having the same method name with different types of parameters or different order of parameters. Method overloading cannot be done by changing only the return type.

public int Add(int a, int b)
{
     a++; // Operator overloading
     Return a+b;
}
// Method overloading. Same method name with different parameters
Public string Add(string a, string b)
{
    Return a+b;
}

It is also called Early Binding. Because call to these functions are decided at compile time itself.

Dynamic Polymorphism

Overriding a virtual method is an example for dynamic polymorphism. It is also known as Late Binding. Because calls to these functions will be decided at runtime only.

public class Animal
{
    Public virtual void Eat()
    {
        //eat by mouth
    }
}
Public class Human
{
    Public override void Eat()
    {
        //Human put food into mouth by hand
        //eat by mouth(by calling base method)
    }
}

Here both method signature are same, so the compiler won’t be knowing which method to be called, it will be decided on runtime.

What is Inheritance in OOPS?

Inheritance

Inheritance is one of the main feature of OOPS. It helps to reuse the code of one class into another by inheriting. Inherited class is called as ‘Base’ or ‘Parent’ class and inheriting class is called as ‘Derived’ or ’Child’ class. By inheriting, the child class can use the properties and functions of base class. This is just like a son/daughter getting some of the behavior from his/her parents. There are different types of inheritance.

  • Single Inheritance
  • Multi Level inheritance
  • Multiple inheritance
  • Hierarchical Inheritance
  • Hybrid Inheritance

Single Inheritance

A single derived class from single base class.

Single Inheritance

Multi Level inheritance

A child class is derived from another child class.The second child class will have all inheritable properties and functions of both base and first child classes.

Multi Level inheritance

Multiple Inheritance

A child class is derived from more than one base class. It is not possible to inherit multiple classes in C#. It is because there is a problem called Diamond Ring problem, which causes conflicts between members of classes. But to overcome the problem, Interfaces are introduced.

Multiple Inheritance

Hierarchical Inheritance

More than one child classes from single base class.

Hierarchical Inheritance

Hybrid Inheritance

It is the combination of all the inheritance. As it is the combination of all inheritance, it include multiple inheritance also, so it’s not supported in C#.

Hybrid Inheritance
References

What is a class in OOPS?

A Class is the blueprint of its objects. Inside the class the programmer can describe the properties and functions required for the behavior of the class. System.Object is the base class of .Net Library.

Syntax of a Class:

public class Human
{
    Public string Name{get;set;}
    Public int Height{get;set;}
    Public string Look{get;set;}

    Public void Run()
    {
        //Do running action
    }
    Public void Talk()
    {
       //Do talking action
    }
}

Class is the type of object

 

What is an Object in OOPS?

Object is the base of object oriented programming concept. Object is an instance of class in programming. In real world, a person is an example of object.

Object
Object

Ex: I’m an object of Human class,

My properties are
Name : Name1
Height : 175 CM
Weight : 75KG
My functions are
Walk(), Run(), Eat(), Talk(), Sleep(), WakeUp() etc.

The same concept is used in programming.

Programmatic representation

Human human1 = new Human();Object
human1.Name = "Name1";
human1.Height = 175;
human1.Weight = 75;