Author: admin

  • 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.

  • C# Enum

    Enum is also known as enumeration that consists of a set of named integral constants. In C#, enumerations are value data types. The keyword enum is used to define these data types.

    The is mainly used to assign the names or string that makes the code more maintainable and readable. For example, we can create an enum for seasons (spring, summer, autumn, winter), or for days(Monday, Tuesday, ….), etc.

    The constant in it is the fixed set of constants and is also known as an enumerator. Enum can also be traversed.

    Syntax of enums

    enum enum_name{const1, const2, ....... };

    • enum_name: Name of the enum given by the user.
    • const1, const2 : These are the value of type enum_name, separated by comma.

    Let us see an example to define enum.

    enum season { spring, summer, autumn, winter };

    The above is the enum for the season, spring, summer, autumn and winter are the types of the season and by default, the value starts in increasing order from zero such as spring is 0, summer is 1, autumn is 2 and winter is 3.


    Example 1: C# program for enum

    using System;
    
    public class EnumEg
    {
      public enum Season
     {
     Spring, Summer, Autumn, Winter
     }
    
      public static void Main()
      {
        int firstSeason = (int) Season.Spring;
        int lastSeason = (int) Season.Winter;
    
        Console.WriteLine("Spring: {0}", firstSeason);
        Console.WriteLine("Winter: {0}", lastSeason);
      }
    }

    Output:

    Spring: 0
    Winter: 3

    As you can see that the default numbers assigned to the constant are shown according to the access. Spring is first on the list so it is 0 and And Winter is at fourth on the list so it is 3 (n-1, starts at 0).


    Example 2: C# program for enum to change the index

    We write a program to change the default indexing of constants in an enum.

    using System;
    
    public class EnumEg
    {
      public enum Season
     {
     Spring = 10, Summer, Autumn, Winter
     }
    
      public static void Main()
      {
        int firstSeason = (int) Season.Spring;
        int secondSeason = (int) Season.Summer;
        int lastSeason = (int) Season.Winter;
    
        Console.WriteLine("Spring: {0}", firstSeason);
        Console.WriteLine("Summer: {0}", secondSeason);
        Console.WriteLine("Winter: {0}", lastSeason);
      }
    }

    Output:

    Spring: 10
    Summer: 11
    Winter: 13

    Now we assign 10 to spring in the list, and from here the increment starts summer becomes 11, and so on. Also, can be seen in the output.


    Example 3: C# program for enum use of getValues()

    We will use getValues and get all the values present in the enum of the season.

    using System;
    
    public class EnumEg
    {
      public enum Season { Spring = 10, Summer, Autumn, Winter
     }
    
      public static void Main()
      {
        foreach(Season s in Enum.GetValues(typeof(Season)))
        {
          Console.WriteLine(s);
        }
      }
    }

    Output:

    Spring
    Summer
    Autumn
    Winter


  • C# Struct

    Struct in C# is a value type and a collection of variables of different data types inside a single unit. It is similar to classes in C# because both are the blueprints to create an object of a class and both are user-defined types.

    However, a struct is a value type whereas a class is a reference type. Also, the struct does not support inheritance but can implement an interface. A class can have a default constructor whereas a struct cannot have a default constructor.

    Syntax of struct in C#

    Defining and Initialization struct in C#: The keyword that is used to define the structure is struct. A structure can also contain constructors, constants, fields, methods, properties, indexers, etc.

    Structures can be instantiated with or without new keyword in C#.

    //Defining
    struct struct_name 
    {  
       // Fields 
       // Parameterized constructor 
       // Methods 
       // Properties 
       // Indexers  
        ... 
        ...  
    };
    
    //Initialization
    struct_name obj = new struct_name();
     

    Consider basic data of student: name, roll, score. And also let us initialized those values by creating an instance of the struct.
    Student structure is declared in the following way:

    //Struct Defining
    public struct Student
    {
       public string name;
       public int roll;
       public float score;
    };
    
    //Initialization
    Student std = new Student();
    std.name = "John Mac";
    std.roll = 1101;
    std.score = 80.5;

    Let us go through an example to understand it better.


    Example 1: C# program for structure

    using System;
    
    public struct Student
    {
      public string name;
      public int roll;
      public float score;
    };
    
    public class StructureEg
    {
      public static void Main(string[] args)
      {
        Student std = new Student();
        std.name = "John Mac";
        std.roll = 1101;
        std.score = 80.5 f;
    
        Console.WriteLine("Name: {0}", std.name);
        Console.WriteLine("Roll: {0}", std.roll);
        Console.WriteLine("score: {0}", std.score);
      }
    }

    Output:

    Name: John Mac
    Roll: 1101
    score: 80.5


    Example 2: C# program for structure using constructor and methods

    It is another program where we will use a constructor and create a method for a structure.

    using System;
    
    public struct Student
    {
      public string name;
      public int roll;
      public float score;
    
      //constructor
      public Student(string n, int r, float s)
      {
        name = n;
        roll = r;
        score = s;
      }
    
      //Method
      public void display()
      {
        Console.WriteLine("Name: {0}", name);
        Console.WriteLine("Roll: {0}", roll);
        Console.WriteLine("score: {0}", score);
      }
    };
    
    public class StructureEg
    {
      public static void Main(string[] args)
      {
        Student std = new Student("John Mac", 1101, 80.5 f);
        std.display();
      }
    }

    Output: The result is the same as example 1 above.

    Name: John Mac
    Roll: 1101
    score: 80.5


  • C# Static Keyword

    Static is a keyword in C# that is when used with different to declare static classes and static class members. Static can be field, method, constructor, class, properties, operator, and event. The instance of a class is not required in order to access static members.

    There is only one copy of the object is created for the static members and is shared among all the objects. Let see the use of static in three areas of the program:

    • static field
    • static method
    • static class

    C# Static Variable or field

    The variable or field in class when declared static is called static field. The difference between static and instance fields is, no matter how many times you create an object for the class, there will be only one memory allocated for the static field of the class and is shared by all the objects.

    But in the case of the instance field, with the creation of every object of the class, a new memory is allocated for the instance field for each object.

    Example: C# example for the static field.

    using System;
    
    class StaticExample
    {
      public static int temp;
    
      public void counter()
      {
        temp++;
      }
    
      public int getTemp()
      {
        return temp;
      }
    }
    
    class StaticMain
    {
      static void Main(string[] args)
      {
        StaticExample st1 = new StaticExample();
        StaticExample st2 = new StaticExample();
    
        st1.counter();
        st1.counter();
    
        st2.counter();
        st2.counter();
    
        Console.WriteLine("Temp count for st1: {0}", st1.getTemp());
        Console.WriteLine("Temp count for st2: {0}", st2.getTemp());
      }
    }

    Output:

    Temp count for st1: 4
    Temp count for st2: 4

    As you can see, no matter which object you use to call, the temp keeps increasing. This indicated that the static field has only one instance and is used by all the other objects.


    C# Static Methods

    The methods that are declared with a static keyword are called static methods. This method can only access the static field of the class.

    Just like a static field, the static function also does not depend on the object of the class. Let us see an example.

    Example: C# example for the static method.

    using System;
    
    class StaticExample
    {
      public static int temp;
    
      public void counter()
      {
        temp++;
      }
    
      public static int getTemp()
      {
        return temp;
      }
    }
    
    class StaticMain
    {
      static void Main(string[] args)
      {
        StaticExample st = new StaticExample();
    
        st.counter();
        st.counter();
    
        Console.WriteLine("Temp count for st: {0}", StaticExample.getTemp());
      }
    }

    Output:

    Temp count for st: 2

    Also, note that the static method can not be invoked with the object of the class. The class name itself is used to invoke the static method. In the above eg. StaticExample.getTemp() is used to invoke the static method getTemp().


    C# static class

    The static class in C# is cannot be instantiated. It can only have static members in its body. And it is created using a static keyword in front of the class like the static field and method.

    Following are some points to remember about static class.

    • The instance of static class cannot be created.
    • To access static members, a class name is used which is followed by the member name.
    • It only has static members and canoot be intatiated.

    Syntax of static class

    public static class class_name  
    {  
       //static data members  
       //static methods  
    }

    Example: C# example for the static class.

    using System;
    
    namespace Program
    {
      public static class Square
      {
       	//static fields  
        public static int side = 10;
    
       	//static method  
        public static void area()
        {
          Console.WriteLine("Area of a square: " + side *side);
        }
      }
    
      class StaticMain
      {
        static void Main(string[] args)
        {
          Console.WriteLine("Side of a square: " + Square.side);
          Square.area();
        }
      }
    }

    Output:

    Side of a square: 10
    Area of a square: 100


  • C# this Keyword

    In C#, this is a keyword that refers to the current instance of a class. It is also used to pass the object to another method as a parameter and also used to call a constructor of another class from the same class in a program.

    It is used to access members from the constructors, instance methods, and instance accessors.

    Let us see an example of this keyword in C# programming.


    Example: C# program for this keyword

    using System;
    
    namespace program
    {
      public class Student
      {
        public int roll;
        public String name;
        public int age;
        public String subject;
    
        //constructor
        public Student(int r, String n, int a, String sub)
        {
          this.roll = r;
          this.name = n;
          this.age = a;
          this.subject = sub;
        }
    
        public void display()
        {
          Console.WriteLine(roll + " " + name + " " + age + " " + subject);
        }
      }
    
      class StudenInfo
      {
        public static void Main(string[] args)
        {
          Student std1 = new Student(1101, "Shaun", 19, "Maths");
          Student std2 = new Student(1102, "Garen", 17, "Computer");
          Student std3 = new Student(1103, "Parker", 18, "Biology");
    
          std1.display();
          std2.display();
          std3.display();
    
        }
      }
    }

    Output:

    1101 Shaun 19 Maths
    1102 Garen 17 Computer
    1103 Parker 18 Biology


  • C# Destructor

    A destructor is the opposite of a constructor. A destructor destroys the object of a class as soon as the scope of an object ends. It is also invoked automatically just like a constructor.

    The destructor cannot have parameters nor modifiers.

    Syntax of destructor in C#

    The destructor has the exact same name as the class, the difference is, it is prefixed with a tilde sign (~).

    //Syntax
    ~ClassName()
    
    //Example
    using System;
    namespace program
    {
        class Square
        {
            ~Square() // destructor
            {
               // statement
            }
        }
    }

    let us see an example of a destructor in C#.


    Example of constructor and destructor in C#

    using System;
    
    namespace program
    {
      public class Student
      {
        public int roll;
        public String name;
        public float score;
    
        //constructor
        public Student(int r, String n, float s)
        {
          roll = r;
          name = n;
          score = s;
        }
    
        public void display()
        {
          Console.WriteLine(roll + " " + name + " " + score);
        }
    
        //Destructor
        ~Student()
        {
           Console.WriteLine("Destructor invoked");
        }
      }
    
      class StudenInfo
      {
        public static void Main(string[] args)
        {
          Student std1 = new Student(1101, "Shaun", 80.5 f);
          Student std2 = new Student(1102, "Garen", 90 f);
    
          std1.display();
          std2.display();
    
        }
      }
    }

    Output:

    1101 Shaun 80.5
    1102 Garen 90
    Destructor invoked
    Destructor invoked