Category: CSharp Tutorial

  • C# Operator Overloading

    We have learned that the method can be overloaded in C#, in the same way, we can also overload the operator. We can perform the various operations with the same operator in C#.

    Operator overloading means performing different operations with the same operator. We can overload most of the built-in operators that are provided by C#. We can also change the user-defined type as well such as structures or classes.

    The keyword ‘operator‘ is used to overload an operator. Compile-time polymorphism is achieved through operator overloading.

    Syntax:

    access_specifier  class_name  operator operator_symbol (argument_list)
    {
        // Code to be executed
    }

    The following table shows which operators present in C# can be overloaded and which are not.

    OperatorsDescription
    +, -, !, ~, ++, – –unary operators take one operand and can be overloaded.
    +, -, *, /, %Binary operators take two operands and can be overloaded.
    ==, !=, =Comparison operators can be overloaded.
    &&, ||Conditional logical operators cannot be overloaded directly
    +=, -+, *=, /=, %=, =Assignment operators cannot be overloaded.

    Also, =, ., ?:, ->, new, is, sizeof, typeof cannot be overloaded.


    Overloading Unary Operators

    The return type of unary operator overloading can be of any type except the void. The unary operator includes +, ~, ! and dot (.), these must have any return type but void but the return type must be the type of ‘Type’ for ++ and – operators and must be a bool type for true and false operators.

    Also, remember that the true and false operators can be overloaded only as pairs. The compilation error occurs if a class declares one of these operators without declaring the other.

    The syntax for overloading unary operator:

    public static classname operator operator_symbol (t)
    {
       // Code to execute
    }

    Let us go through an example in the C# program for overloading unary operators.

    using System;
    class Example
    {
      private int x;
      private int y;
      public Example() {}
    
      public Example(int i, int j)
      {
        x = i;
        y = j;
      }
    
      public void print()
      {
        Console.WriteLine("X = {0}  Y = {1}", x, y);
      }
    
      public static Example operator-(Example eg)
      {
        eg.x = -eg.x;
        eg.y = -eg.y;
        return eg;
      }
    }
    
    class MainFunc
    {
      public static void Main()
      {
        Example obj1 = new Example(10, 20);
        obj1.print();
    
        Example obj2 = new Example();
        obj2 = -obj1;
    
        obj2.print();
      }
    }

    Output:

    X = 10 Y = 20
    X = -10 Y = -20


    Overloading Binary Operator

    Binary operators are overloaded in pairs such as when an arithmetic operator is overloaded then the corresponding assignment operators also get overloaded automatically. For example, if we overload the + operator then += also gets overloaded automatically.

    The syntax for overloading binary operator:
    we overload binary operator in the same manner as a unary operator, the only difference is the number of parameters here is two.

    public static classname operator operator_symbol (t1, t2)
    {
      // Code to be executed
    }
    using System;
    
    namespace BinaryOverloading
    {
      class Example
      {
        private int num1;
        private int num2;
    
        //constructor with no argument
        public Example() {}
    
        public Example(int i, int j)
        {
          num1 = i;
          num2 = j;
        }
    
        public void print()
        {
          Console.WriteLine("num1 = {0}  num2 = {1}", num1, num2);
        }
    
        public static Example operator+(Example eg1, Example eg2)
        {
          Example temp = new Example();
          temp.num1 = eg1.num1 + eg2.num1;
          temp.num2 = eg1.num2 + eg2.num2;
          return temp;
        }
      }
    
      class MainBinary
      {
        public static void Main()
        {
          Example obj1 = new Example(10, 20);
          obj1.print();
    
          Example obj2 = new Example(20, 30);
          obj2.print();
    
          Example obj3 = new Example();
          obj3 = obj1 + obj2;
    
          obj3.print();   //final result  
        }
      }
    }

    Output:

    num1 = 20 num2 = 30
    num1 = 10 num2 = 20
    num1 = 30 num2 = 50


  • C# Method Overriding

    Method overriding is done through inheritance, it allows us to define a method at a derived class with the same name present in a base class with the same signature and same return type then the method in a base class is said to be overridden.

    In method overriding, the base class method uses virtual keyword while the derived class method uses override keyword.

    Method overriding is one of the ways through which C# achieves Run Time Polymorphism (Dynamic Polymorphism). The decision made to call the required function is done at the run time. Hence, it is a Runtime polymorphism.

    Example: C# program for method overriding.

    using System;  
    
    namespace Program 
    {
     public class Animal
     {  
        public virtual void sleep()
        {  
            Console.WriteLine("Animals Sleeps");  
        }  
     }  
     public class Dog: Animal  //inheriting Animal class
     {  
        public override void sleep()  
        {  
            Console.WriteLine("Dog Sleeps");  
        }  
          
     }  
    
     public class OverrideMain
     {  
        public static void Main()  
        {  
            Animal obj = new Dog();  
            obj.sleep();  
            
            obj = new Animal();
            obj.sleep(); 
        }  
     }  
    }

    Output:

    Dog Sleeps
    Animals Sleeps


  • C# Method Overloading

    A method is said to be overloaded if two or more methods having the same name but different parameters. The difference could be in a number of parameters or types of parameters so that compiler can tell the difference.

    The advantage of method overloading is that you don’t have to use different names for the function which does the same task. Method overloading is a way to achieve Compile Time Polymorphism in C#

    Method overloading in C# can be achieved in two ways:

    1. By changing number of arguments
    2. By changing data type of the arguments

    1. C# Method overloading: By changing the data type of Arguments

    In this method, the data type is changed although the number of arguments passed remains the same. Also, while calling this method make sure to give the proper parameters accordingly.

    Example of C# program for method overloading.

    using System;
    
    namespace Program
    {
      class OverloadMethod
      {
        public void display(String name, int roll)
        {
          Console.WriteLine("Name: {0}  Roll: {1}", name, roll);
        }
    
        public void display(float num1, float num2)
        {
          Console.WriteLine("Value of counter: {0}", num1 + num2);
        }
      }
    
    public class OverloadMain
    {
        static void Main(string[] args)
        {
          OverloadMethod obj = new OverloadMethod();
    
          // Call functions
          obj.display("John Mac", 18);
          obj.display(90.2f, 6.5f);
        }
      }
    }

    Output:

    Name: John Mac Roll: 18
    Value of counter: 96.7


    2. C# Method Overloading: By changing no. of arguments

    Another way is by changing the number of arguments that is the number of parameters passed when called. We can also keep the argument empty and it will recognize the method with an empty parameter list.

    Example of C# program for method overloading.

    using System;
    
    namespace Program
    {
      class MethodOverload
      {
        public void display(String name, int roll)
        {
          Console.WriteLine("Name: {0}  Roll: {1}", name, roll);
        }
    
        public void display(int counter)
        {
          Console.WriteLine("Value of counter: {0}", counter + 1);
        }
      }
    
    public class OverloadMain 
    {
        static void Main(string[] args)
        {
          MethodOverload obj = new MethodOverload();
    
          // Call functions
          obj.display("John Mac", 18);
          obj.display(99);
        }
      }
    }

    Output:

    Name: John Mac Roll: 18
    Value of counter: 100


  • C# Polymorphism

    Polymorphism means having many forms. The word “poly” means many and “morphs” means form. Polymorphism is one of the core principles of object-oriented programming which means it is the way of performing some task in many ways.

    With polymorphism, a class can have multiple implementations with the same name.

    There are two types of polymorphism in C#:

    1. Compile-time Polymorphism or Static (or early) Polymorphism.
    2. Runtime Polymorphism or Dynamic (or late) Polymorphism.

    C# Compile Time Polymorphism

    In this type of program, the flow of control is decided at compile time itself. It is achieved by function overloading and operator overloading. It is also known as static or early binding.

    Let us go through function overloading and we will cover operator overloading in the next tutorial.

    Function Overloading

    A function is said to be overloaded if two or more functions having the same name but different parameters. The difference could be in a number of parameters or types of parameters so that compiler can tell the difference.

    Also, while calling this function make sure to give the proper parameters according to the required called function. Learn more on method overloading in C#.

    Example of C# program for function overloading.

    using System;
    
    namespace Program
    {
      class PolyExample
      {
        void display(String name, int roll)
        {
          Console.WriteLine("Name: {0}  Roll: {1}", name, roll);
        }
    
        void display(int counter)
        {
          Console.WriteLine("Value of counter: {0}", counter + 1);
        }
    
        //Main function
        static void Main(string[] args)
        {
          PolyExample obj = new PolyExample();
    
          // Call functions
          obj.display("John Mac", 18);
          obj.display(99);
        }
      }
    }

    Output:

    Name: John Mac Roll: 18
    Value of counter: 100


    C# Run Time Polymorphism

    In run time polymorphism, the program is called at the time of execution that is at rum time. It is also known as the late binding or dynamic binding.

    This type of polymorphism is achieved by Method Overriding.

    Method Overriding

    Method overriding is done through inheritance, it allows us to define a function at a derived class that is already present in a base class. And that base is said to be overridden. There is a use of the virtual keyword and override keyword as shown in the program below.

    And the decision made to call the required function is done at the run time. Hence, the Runtime polymorphism.

    Example: C# program for method overriding.

    using System;  
    
    namespace Program {
     public class Animal
     {  
        public virtual void sleep()
        {  
            Console.WriteLine("Animals Sleeps");  
        }  
     }  
     public class Dog: Animal  //inheriting Animal class
     {  
        public override void sleep()  
        {  
            Console.WriteLine("Dog Sleeps");  
        }  
          
     }  
    
     public class PolymorphismMain
     {  
        public static void Main()  
        {  
            Animal obj = new Dog();  
            obj.sleep();  
            
            obj = new Animal();
            obj.sleep(); 
        }  
     }  
    }

    Output:

    Dog Sleeps
    Animals Sleeps


  • C# Properties

    C# properties are the class members that provide a flexible way for the class to expose its private field. It provides a way to read, write, and perform some computation to the private fields of the class.

    These properties have special methods called accessors that are used to set, get, and compute on private fields of the class. The two accessors used are the get accessor and set accessor.

    • get accessor: It specifies read-only property and returns a property value. We use it to get the private filed value as a public.
    • set accessor: It specifies write-only property and returns a property value. We use it to assign a new value to the private filed.

    The properties can be read-only, write-only, or read-write property. The read-only implements get an accessor but no set accessor. The write-only implements set accessor but no get accessor whereas read-write implements both set and get accessors.

    We use it in the following way in a program:

    private String name;
    private int age;
    
    // Name as a String type
    public string Name
    {
      get
      {
        return name;
      }
      set
      {
        name = value;
      }
    }
    
    // Age as an int type
    public int Age
    {
      get
      {
        return age;
      }
      set
      {
        age = value;
      }
    }

    Let us go through a program to understand its use.


    Example 1: C# program for Properties

    We will write a program for a read-write property using a set and get accessors.

    using System;
    
    public class Student
    {
      // private variables
      private String name;
      private int roll;
    
      // using setter and getter for name
      public String stdName
      {
        get
        {
          return name;
        }
    
        set
        {
          name = value;
        }
      }
    
      // using setter and getter for roll
      public int stdRoll
      {
        get
        {
          return roll;
        }
    
        set
        {
          roll = value;
        }
      }
    }
    
    class StudentInfo
    {
      static public void Main()
      {
        // creating object
        Student obj = new Student();
    
        //setting the values
        obj.stdName = "John Mac";
        obj.stdRoll = 15;
    
        // Getting the values
        Console.WriteLine("Student Name: " + obj.stdName);
        Console.WriteLine("Studen Roll: " + obj.stdRoll);
      }
    }

    Output:

    Student Name: John Mac
    Studen Roll: 15


    Example 2: C# program for read-only Properties

    using System;
    
    public class Student
    {
      // private variables
      private String name;
      private int roll;
    
      public Student(String n, int r)
      {
        name = n;
        roll = r;
      }
    
      // using get
      public String stdName
      {
        get
        {
          return name;
        }
      }
    
      // using get
      public int stdRoll
      {
        get
        {
          return roll;
        }
      }
    }
    
    class StudentInfo
    {
      static public void Main()
      {
        // creating object
        Student obj = new Student("Jacob Hill", 17);
    
        // Getting the values
        Console.WriteLine("Student Name: " + obj.stdName);
        Console.WriteLine("Studen Roll: " + obj.stdRoll);
      }
    }

    Output:

    Student Name: Jacob Hill
    Studen Roll: 17


  • C# Namespace

    Namespace in C# is used in a program to organize the code separately from each other. Classes are maintained with namespace to organize in a better way.

    With the use of namespace, we can keep one set of names different from another set of names. The vital importance of namespace is that it prevents the collision of the same class names declared in two different namespaces.

    A namespace can have Namespaces (Nested Namespace), Classes, Interfaces, Structures, and Delegates.

    Defining a Namespace

    The keyword “namespace” is used to define the namespace and the namespace can be nested.
    Syntax:

    namespace name_of_namespace 
    {
    
       // Namespace (Nested Namespaces)
       // Classes
       // Interfaces
    
       . . . . . 
    
       . . . . . .
    }

    Sample example of the namespace:

    namespace NamespaceEg
    {
        class ClassEg
        {
            public void method_1()
            {
                System.Console.WriteLine("Namespace created");
    	}
        }
    }

    Accessing members of namespace in C#

    The members of the namespace can be accessed using dot(.) operator. The syntax for accessing namespace members is as followed.

    namespace_name.member_name

    Remember that, two classes inside the same namespace cannot have the same name but the class from a different namespace may have the same class name.


    Example 1: C# program to demostrate Namespace

    using System;
    
    namespace first_ns
    {
      class ClassGreet
      {
        public void func()
        {
          Console.WriteLine("This is First Namespace");
        }
      }
    }
    
    namespace second_ns
    {
      class ClassGreet
      {
        public void func()
        {
          Console.WriteLine("This is Second Namespace");
        }
      }
    }
    
    class TestClass
    {
      static void Main(string[] args)
      {
        first_ns.ClassGreet f_ns = new first_ns.ClassGreet();
        second_ns.ClassGreet s_ns = new second_ns.ClassGreet();
        f_ns.func();
        s_ns.func();
      }
    }

    Output:

    This is First Namespace
    This is Second Namespace

    As you can see in the above program, the name of the classes are the same inside the two different namespaces and still, the program did not get affected. We created two different objects for two different namespaces classes and accessed the functions respectively.


    The using Keyword

    A namespace can be included in the program with the help of using keyword. We already use a name using keyword for System in a program.

    Using System in a program we are able to write Console.WriteLine(Hello Simple2code.com") instead of writing the whole System.Console.WriteLine(Hello Simple2code.com"). We include it in the following in the program.

    using namespace_name;

    Let us go through the above program again and rewrite it using the using keyword.

    using System;
    
    using first_ns;
    using second_ns;
    
    namespace first_ns
    {
      class FirstGreet
      {
        public void func()
        {
          Console.WriteLine("This is First Namespace");
        }
      }
    }
    
    namespace second_ns
    {
      class SecondGreet
      {
        public void func()
        {
          Console.WriteLine("This is Second Namespace");
        }
      }
    }
    
    class TestClass
    {
      static void Main(string[] args)
      {
        FirstGreet f_ns = new FirstGreet();
        SecondGreet s_ns = new SecondGreet();
        f_ns.func();
        s_ns.func();
      }
    }

    Output:

    This is First Namespace
    This is Second Namespace


    Nested Namespaces in C#

    We can also nest the namespace in a program as already told above. It means inserting a namespace inside a namespace in a program and its members can also be accessed with the use of dot (.) operator.

    Syntax of the nested namespace:

    namespace outer_namespace
    {
        namespace inner_namespace
        {
            // Body of innner namespace
        }
    }

    Example: C# program for the nested namespace

    using System;
    
    namespace Main_ns
    {
      namespace Nested_ns
      {
        class GreetClass
        {
          public void greet()
          {
            Console.WriteLine("Welcome to simple2code.com");
          }
        }
      }
    }
    
    class MainClass
    {
      static void Main(string[] args)
      {
        Main_ns.Nested_ns.GreetClass f_ns = new Main_ns.Nested_ns.GreetClass();
        f_ns.greet();
      }
    }

    //Output
    Welcome to simple2code.com

    If you don’t want to write the whole statement of the main class to create an object then you can simply use using keyword to include the namespace in the following way.

    Write the following at the beginning of the program.

    using Main_ns;
    using Main_ns.Nested_ns;

    And do the following inside the main function of the program.

    class MainClass
    {
      static void Main(string[] args)
      {
        GreetClass f_ns = new GreetClass();
        f_ns.greet();
      }
    }

    The output will be the same but you don’t have o repeat the long code again and again in the program.


  • C# Interface

    An Interface is the same as a class, it is a blueprint of a class. Just like any other class, an interface can have methods, properties, events, and indexers as its members. But unlike a class, the method in it is an abstract method (only method signature, contain no body).

    • Interface is used to achieve abstraction and multiple inheritance which cannot be achieved through the class.
    • An interface specifies what a class must do but not how to hence the abstraction.
    • By deafult, the members of interface are public and abstract. It cannot have private members.

    Declaring an interface

    The keyword interface is used to declare an interface and is done just like a class as shown below.

    specifier interface interface_name
    {
        // declare Events
        // declare indexers
        // declare methods 
        // declare properties
    }

    Example:

    public interface Animal 
    {
      void animalSound(); 
      void run();
    }

    Implementation of an interface is done in the following way on a class.

    //implementing interface
    class className : interfaceName

    Example 1: C# program to illustrate interface

    using System;
    
    public interface IAnimal
    {
      void sound();
    }
    
    // implementing interface to class
    public class Dog: IAnimal
    {
      public void sound()
      {
        Console.WriteLine("The dog barks: woof woof");
      }
    }
    
    //main class
    public class INterfaceMain
    {
      static void Main(string[] args)
      {
        Dog obj = new Dog();
        obj.sound();
      }
    }

    Output:

    The dog barks: woof woof


    Multiple Interface

    We can create multiple interfaces in a program having different tasks and use them in the same class. And to implement multiple interfaces in the same class we separate them with commas in between as shown in the program below.

    Example 2: C# program to illustrate multiple interface

    using System;
    
    public interface IDog
    {
      void barks();
    }
    
    public interface ICat
    {
      void meows();
    }
    
    // implementing multiple interface to class
    public class Animal: IDog, ICat
    {
      public void barks()
      {
        Console.WriteLine("The Dog barks.");
      }
    
      public void meows()
      {
        Console.WriteLine("The Cat Meows.");
      }
    }
    
    //main class
    public class INterfaceMain
    {
      static void Main(string[] args)
      {
        Animal obj = new Animal();
        obj.barks();
        obj.meows();
      }
    }

    Output:

    The Dog barks.
    The Cat Meows.


  • C# Abstraction

    Abstraction in object-oriented programming is a way to hide the details and only displaying the relevant information to the users. It is a technique through which we can separate the interface with the implementation details.

    Abstraction and encapsulation are the related feature in C#. Abstraction is used to hide the implementation detail while encapsulation is a way to achieve the desired level of abstraction.

    Take a real-life example:
    Suppose you are switching the channel with your TV remote control. You click the button to switch to the desired channel on a TV but how the implementation of switching channel with a click of a button is unknown to you, that is an abstraction. It hides the detail of how the work is done inside the remote control. The users are only familiar with the button and how to operate with the button.

    In C#, abstraction can be achieved in two ways.

    • Abstract class.
    • Interfaces.

    Let us first see an abstract method.

    Abstract Method

    Abstraction and interface both have abstract methods. The method that has no body is called the abstract method. An abstract method is also declared with an abstract keyword and ends with a semicolon(;) instead of curly braces({}).

    Syntax of abstract method:

    public abstract void methodName();


    C# Abstract Class

    In C#, the class declared with an abstract keyword is called an abstract class. An abstract class may or may not have abstract methods.

    An object of abstract class cannot be created in C#, to access this class, it must be inherited from another class.

    Syntax of an abstract class:

    abstract class ClassName {
    . . . . .
    }

    Let us go through an example of an abstract class in C#


    Example: C# program for an abstract method

    In the example below, we create an abstract class with an abstract method that is inherited by another class.

    using System;
    
    //abstraction class
    public abstract class Animal
    {
      //abstraction method
      public abstract void sound();
    }
    
    public class Dog: Animal
    {
      //override abstraction method
      public override void sound()
      {
        Console.WriteLine("Dog barks");
      }
    }
    
    public class Cat: Animal
    {
     	//override abstraction method
      public override void sound()
      {
        Console.WriteLine("Cat Meows");
      }
    }
    
    public class AbstractMain
    {
      public static void Main()
      {
        Animal dg = new Dog();
        Animal ct = new Cat();
    
        dg.sound();
        ct.sound();
      }
    }

    Output:

    Dog barks
    Cat Meows


    Advantage of data abstraction

    • It also avoids code duplication increases the reusability of the code.
    • Since the abstraction separates the interface and implementation, the internal changes can be easily made without affecting the user-level code.
    • The abstracting of the data itself increases the security as no user can access the internal hidden mechanism.

  • C# Access Modifiers/Specifiers

    Access modifiers or specifiers in C# define the accessibility of the member, class, or datatype in a program. These are the keyword that restricts unwanted manipulation of data in a program by other classes.

    There are five types of access specifiers in C#.

    1. Public
    2. Protected
    3. Internal
    4. Protected internal
    5. Private

    Let us go through each of them with an example.

    Public Access Specifier

    Declaring fields and methods or classes public means making it accessible everywhere in a program or in an application. It is accessed by the entire program. Any public member can be accessed from outside the class.

    Example: C# program to demonstrate public access specifier.

    using System;
    
    namespace Program
    {
      class Student
      {
        public string name;
        public int age;
    
        public Student(String n, int a)
        {
          name = n;
          age = a;
        }
    
        public void print()
        {
          Console.WriteLine("Name: {0}", name);
          Console.WriteLine("Age: {0}", age);
        }
      }
    
      class PublicAccess
      {
        static void Main(string[] args)
        {
          Student obj = new Student("John Mac", 15);
    
          // Accessing public method  
          obj.print();
    
          // Accessing public variable name 
          Console.WriteLine("My name is: {0}", obj.name);
    
        }
      }
    }

    Output:

    Name: John Mac
    Age: 15
    My name is: John Mac


    Protected Access Specifier

    Declaring fields and methods protected means limiting its accessibility only to its class and derived types of this class. In the case of inheritance, the sub-class can access the private member of the derived class.

    Example: C# program to demonstrate protected access specifier.

    using System;
    
    namespace protectedAccess
    {
      class Animal
      {
        protected String str = "Animals";
    
        protected void eat()
        {
          Console.WriteLine(str + " eat.");
        }
      }
    
      // Dog class inherits Animals Class
      class Dog: Animal
      {
        public void sound()
        {
          eat();  //Accessing protected member
          Console.WriteLine("Barking...");
        }
      }
    
      class Program
      {
        static void Main(string[] args)
        {
          Dog obj = new Dog();
    
          // Accessing through the child class
          obj.sound();
        }
      }
    }

    Output:

    Animals eat.
    Barking…


    Internal Access Specifier

    Declaring fields, methods, or class internal means limiting its accessibility only within files in the current assembly. It is a default specifier in the C# program, internal members can be accessed anywhere within its namespace.

    Example: C# program to demonstrate internal access specifier.

    using System;
    
    namespace Program
    {
      class Student
      {
        internal string name = "Jason Marsh";
    
        internal void print(int age)
        {
          Console.WriteLine("Age: {0}", age);
        }
      }
    
      class PublicAccess
      {
        static void Main(string[] args)
        {
          Student obj = new Student();
    
          // Accessing internal variable name 
          Console.WriteLine("My name is: {0}", obj.name);
    
          // Accessing internal method  
          obj.print(16);
    
        }
      }
    }

    Output:

    My name is: Jason Marsh
    Age: 16


    Protected Internal Access Specifier

    Declaring fields or methods protected internal means limiting its accessibility to the current assembly and within a derived class in another assembly.

    Example: C# program to demonstrate protected internal access specifier.

    using System;
    
    namespace Program
    {
      class Student
      {
        protected internal string name = "Jason Marsh";
    
        protected internal void print(int age)
        {
          Console.WriteLine("Name: {0}", age);
        }
      }
    
      class PublicAccess
      {
        static void Main(string[] args)
        {
          Student obj = new Student();
    
          // Accessing internal variable name 
          Console.WriteLine("My name is: {0}", obj.name);
    
          // Accessing internal method  
          obj.print(16);
    
        }
      }
    }

    Output:

    My name is: Jason Marsh
    Age: 16


    Private Access Specifier

    It is specified using the private keyword. Variables, Methods, and constructors that are declared private modifiers are only accessed within the declared class itself. It is the most access restricting specifier among all. This specifier is mostly used when you want to hide your members.

    It is used to achieve encapsulation in C#. If you want to access the data, we use the set and get method.

    Example: C# program to demonstrate private access specifier.

    using System;
    
    public class Student
    {
      // private variables
      private String name;
      private int roll;
    
      // using setter and getter for name
      public String stdName
      {
        get
        {
          return name;
        }
    
        set
        {
          name = value;
        }
      }
    
      // using setter and getter for roll
      public int stdRoll
      {
        get
        {
          return roll;
        }
    
        set
        {
          roll = value;
        }
      }
    }
    
    class StudentInfo
    {
      static public void Main()
      {
        // creating object
        Student obj = new Student();
    
        //setting the values
        obj.stdName = "John Mac";
        obj.stdRoll = 15;
    
        // Getting the values
        Console.WriteLine("Student Name: " + obj.stdName);
        Console.WriteLine("Studen Roll: " + obj.stdRoll);
      }
    }

    Output:

    Student Name: John Mac
    Studen Roll: 15


  • C# Encapsulation

    Encapsulation is an important concept of Object-oriented programming. Encapsulation is the concept of wrapping up data(variable) under a single unit. It binds data members and member functions inside a class together.

    Encapsulation prevents accessing the implementation details, it makes sure that the ‘sensitive’ data are hidden from the user which leads to the important concept called data hiding. Abstraction and Encapsulation are quite related features, encapsulation helps us to achieve the desired level of abstraction.

    Access specifiers are used to achieve encapsulation. We can do so by declaring all the variables in a class private. But in order to modify or read those data or variables, we need to use the getter and setter (i.e. get and set) method. It prevents from accessing the data directly.

    Let us go through an example in C# to understand the concept of hiding data.


    Example: C# program for hiding data using the private specifier

    There is a separate class for the student whose data members are private so get and set methods are implemented for each private variable in order to access it from the main function of the program.

    using System;
    
    public class Student
    {
      // private variables
      private String name;
      private int roll;
    
      // using setter and getter for name
      public String stdName
      {
        get
        {
          return name;
        }
    
        set
        {
          name = value;
        }
      }
    
      // using setter and getter for roll
      public int stdRoll
      {
        get
        {
          return roll;
        }
    
        set
        {
          roll = value;
        }
      }
    }
    
    class StudentInfo
    {
      static public void Main()
      {
        // creating object
        Student obj = new Student();
    
        //setting the values
        obj.stdName = "John Mac";
        obj.stdRoll = 15;
    
        // Getting the values
        Console.WriteLine("Student Name: " + obj.stdName);
        Console.WriteLine("Studen Roll: " + obj.stdRoll);
      }
    }

    Output:

    Student Name: John Mac
    Studen Roll: 15


    Advantages of Encapsulation:

    • Data- hiding and Reusability.
    • The class field can be made read-only or write-only.
    • It provides the class the total control over the data.