Category: CSharp Tutorial

  • 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


  • C# Constructor

    In C#, a constructor is the member of the class and is automatically invoked once the object of the class is created. It is like a method in a program and is used for the initialization of the data members of a newly created object.

    class Example
    {   
      .......
      // Constructor
      public Example() {
        //Object initialization  
      }
      .......
    }
    
    
    //creating oject
    Example obj = new Example(); 

    Two types of C# constructors

    1. Default constructor
    2. Parameterized constructor

    Default Constructor in C#

    A constructor without any parameters is called a default constructor and is invoked at the time of creating the object of the class.

    Example: Default C# Constructor

    using System;  
    
       public class Student  
       {  
          public Student()  
          {  
              Console.WriteLine("Constructor Called");  
          }  
          public static void Main(string[] args)  
          {  
              Student std1 = new Student();  
              Student std2 = new Student();  
          }  
       }  

    Output:

    Constructor Called
    Constructor Called

    As you can see, that the constructor is called every time we create a new object of the class. And since it is a default constructor, it has no parameter.


    Parameterized Constructor in C#

    A Constructor having a specific number of parameters is called Parameterized Constructor. Passing parameters is useful when you want to assign a different initial value to distinct objects.

    Example: Parameterized C# Constructor

    using System; 
     
     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);  
         }  
     }  
    
     class StudenInfo
     {  
        public static void Main(string[] args)  
        {  
           Student std1 = new Student(1101, "Shaun", 80.5f);  
           Student std2 = new Student(1102, "Garen", 90f);  
                
           std1.display();  
           std2.display();  
      
        }  
     }   

    Output:

    1101 Shaun 80.5
    1102 Garen 90

    As you can see the student details are initialized and displayed for every object created for the Student class in a program.


  • C# Object and Class

    C# is an object-oriented programming language and classes and objects are the fundamental components of OOP’s. Everything in C# is built upon classes and objects. Let us learn classes and objects with an example.

    C# Class

    A class is a user-defined blueprint or prototype for creating Objects. We can say that it is a template for creating objects for a class.

    A class can have fields, methods, constructors, etc and these members can be accessed and used by creating an instance of that class that is an object.

    Example for defining a class with few fields and methods in C#.

    public class Rectangle
     {  
    
        //field
        int length, breadth;
        int area;   
        
        // method
        public void area() {
           area = length * breadth;
        } 
     }  

    The definition of the class starts with the keyword class followed by a class name. The body of the class is enclosed within the curly brace. All the members of the class are declared within the body of the class as shown above.


    C# Object

    Objects are real-world entities. Example bike, Lamp, pen, table, etc. It is an instance of a class that has states and behavior. It can be physical and logical.

    The Class members are accessed by creating an object of that class and is a runtime entity created at runtime.

    To create an object of a class we use the keyword new.

    //creating an object of class Rectangle
    Rectangle rect = new Rectangle();

    In the above code, Rectangle is a type and rect is a reference variable that refers to the instance of the Rectangle class. And the new keyword allocates the memory at runtime in a program.


    Example1: C# Class and Object

    Let see an example where we create a class Rectangle and have a method calculate the area and also display the area value.

    using System;  
    
    public class Rectangle
     {  
        //field
        int length = 2, breadth = 3;
        int area;   
        
        // method
        public void areaFunc() 
        {
           area = length * breadth;
           Console.WriteLine("Area: {0}", area);
        } 
        
        public static void Main(string[] args) 
        {
            Rectangle rect = new Rectangle(); //object
            rect.areaFunc();
         }
     }

    Output:

    Area: 6


    Example1: C# Class and Object

    In the example below, we will put the main method at the different classes and create multiple objects for the Student class. Also, display the student information.

    using System;  
    
    public class Student
     {  
        //field
        int roll = 2;
        String name;  
        
        //Constructor
        public Student (int r, String str)
        {
            this.roll = r;
            this.name = str;
        }
        
        // method
        public void display() 
        {
           Console.WriteLine("Roll: {0}, Name: {1}", roll, name);
        } 
        
     }
     
     class StudentInfo
     {
        public static void Main(string[] args) 
        {
            Student std1 = new Student(1, "John Mac"); //object
            Student std2 = new Student(2, "Ryan Blanc"); //object
            
            std1.display();
            std2.display();
         }
     }
     

    Output:

    Roll: 1, Name: John Mac
    Roll: 2, Name: Ryan Blanc

    Also, a constructor is included in order to initialize the class field.


  • C# Array Class

    There are various operations that can be done with an array such as creating, manipulating, sorting, searching, etc. This is done by the array class that provides various methods to perform mentioned operation in C#.

    Note: In C#, Array is not part of the collection but considered as a collection because it is based on the IList interface.


    Properties of the Array Class – C#

    The following table represents some of the properties of the Array class that are mostly used.

    PropertyDescription
    IsFixedSizeThis property is used to get a value indicating whether the Array has a fixed size or not.
    IsReadOnlyThis is used to check whether the Array is read-only or not.
    LengthThis property gets (32-bit integer) that represents the total number of elements in all the dimensions of the Array.
    LongLengthThis property gets (a 64-bit integer) that represents the total number of elements in all the dimensions of the Array.
    RankThis property gets the rank (number of dimensions) of the Array.
    SyncRootIt gets an object that can be used to synchronize access to the Array.
    IsSynchronizedIt checks whether the access to the Array is synchronized.

    Methods of the Array Class – C#

    The following table represents some of the methods of the Array class that are mostly used.

    MethodDescription
    BinarySearch()This method is used to search an entire one-dimensional sorted array for a specific value. It uses binary search algorithm
    Clear()It is used to set a range of elements to zero, to null, or to false, depending on the type of element.
    Empty()Simply returns an empty array.
    Copy()This method copies elements of an array into another array by specifying the initial index and performs type casting as required.
    CopyTo()Copies all the elements of the current one-dimensional array to the specified one-dimensional array.
    Clone()This method creates a shallow copy of the Array.
    CreateInstance()Using this method new instance of the Array class is initialized.
    Initialize()This method initializes every element of the value-type Array by calling the default constructor of the value type.
    IndexOf()This method searches for the specified object and returns the index of the first occurrence in a one-dimensional array.
    Find()It is used to search for an element that matches the conditions defined by the specified predicate and returns the first occurrence within the entire Array.
    Reverse()This method reverses the sequence of the elements in the entire one-dimensional Array.
    ToString()It returns a string that represents the current object.
    GetUpperBound()It is used to get the upper bound of the specified dimension in the Array.
    GetLowerBound()It is used to get the lower bound of the specified dimension in the Array.
    Sort()It is used to sort the elements in an entire one-dimensional Array by using the IComparable implementation of each element of the Array..
    AsReadOnly()This method returns a read-only wrapper for the specified array.

    C# program for Array Class

    No let us see an example to demonstrate some of the methods of Array Class in C# programming.

    using System;
    
    namespace ArrayClass
    {
       class Program
       {
          //We will call this printing function if we want to print in the main program
          // User defined method 
          static void DisplayFunc(int[] arr)
          {
             foreach(Object elem in arr)
             {
                Console.Write(elem + " ");
             }
          }
    
          static void Main(string[] args)
          {
             // Creating an array and initializing it 
             int[] arr = new int[5]
             { 10, 2, 3, 8, 77 };
    
             // Print length of array  
             Console.WriteLine("Length of an Array: " + arr.Length);
    
             // Finding index of an array element using IndexOf()
             Console.WriteLine("Index of 3 in an array: " + Array.IndexOf(arr, 3));
    
             // Creating an empty array to copy  
             int[] copied_arr = new int[6];
             Array.Copy(arr, copied_arr, arr.Length);
             Console.Write("Copied Array (copied_arr): ");
             DisplayFunc(copied_arr);
    
             // Sorting an array   
             Array.Sort(arr);
             Console.Write("\nSorted array (arr): ");
             DisplayFunc(arr);
    
             //Reverse an array
             Array.Reverse(arr);
             Console.Write("\nFirst Array elements in reverse order: ");
             DisplayFunc(arr);
          }
       }
    }

    Output:

    Length of an Array: 5
    Index of 3 in an array: 2
    Copied Array (copied_arr): 10 2 3 8 77 0 
    Sorted array (arr): 2 3 8 10 77 
    First Array elements in reverse order: 77 10 8 3 2 

  • C# Params Array

    Sometimes a situation may arise where you do not know how many parameters you want to pass to a method or you may want the method to accept n number of parameters at runtime. In such times params type array can solve the problem. param is a keyword in C# that creates an array at runtime that receives and holds as many numbers of parameters as you want.

    The length of params will be zero if no arguments will be passed. Although only one params keyword is allowed and no other parameters are allowed after the method declaration.

    Let us see it in a program.


    C# Program to demonstrate the params Array

    Let us create two classes, one class will contain the method and another class where the main class will be present. The method will be accessed by creating an instance of the class in the main function.

    using System;
    
    namespace Arrays
    {
       class ParamsArray
       {
          public int SumElements(params int[] arr)
          {
             int sum = 0;
    
             foreach(int i in arr)
             {
                sum += i;
             }
    
             return sum;
          }
       }
    
       //main function class
       class MainClass
       {
          static void Main(string[] args)
          {
             //creating an object of ParamsArray class
             ParamsArray paramArray = new ParamsArray();
             int result = paramArray.SumElements(10, 20, 30, 40, 50);
    
             Console.WriteLine("The sum of the result: {0}", result);
          }
       }
    }

    Output:

    //Output:
    The sum of the result: 150

    Example: C# Program to pass different data-types and print them

    Let us see another example where we pass different data-type inputs and print them all with param. We will use object type params that allow us to enter as many numbers of inputs as we want of different data types.

    using System;
    
    namespace Arrays
    {
       class ParamProgram
       {
          // Print function (user-defined)
          public void DisplayFunc(params object[] elements)
          {
             Console.WriteLine("Displaying all the different types elements:");
             for (int i = 0; i < elements.Length; i++)
             {
                Console.WriteLine(elements[i]);
             }
          }
    
          // Main function
          static void Main(string[] args)
          {
             // Creating Object of class ParamProgram
             ParamProgram program = new ParamProgram();
    
             // Passing arguments of different types
             program.DisplayFunc("John Snow", 456, 30.25, "simple2code.com", 'Z', "Coder");
          }
       }
    }

    Output:

    //Output:
    The sum of the result: 150

  • C# Passing Array to Function

    In this tutorial, we will learn how to pass an array to function in C#. Before that you need to have an idea on following topics in C#.

    We use a function to reuse a block of code in a program. And we can pass an array to the function as a parameter. To pass an array, we need to provide an array name as an argument of a function. Example:

    //passing array 
    function_name(array_name); 

    C# Passing Array to Function

    Let us see it in a demonstration for passing an array to a function in C#. We will pass an array and find the largest element in a function.

    //C# program to fincd largest element in an array
    
    using System;
    
    namespace Arrays
    {
       public class ArrayToFunction
       {
          static void maxElement(int[] arr, int arr_size)
          {
             int max = arr[0];
             for (int i = 1; i < arr_size; i++)
             {
                if (max < arr[i])
                {
                   max = arr[i];
                }
             }
    
             Console.WriteLine("Largest element is: " + max);
          }
    
          public static void Main(string[] args)
          {
             int[] arr = { 77, 85, 98, 14, 50 };
    
            	//passing array to function
             maxElement(arr, 5);
          }
       }
    }

    Output:

    Largest element is: 98

    Another Example: C# Program to find the sum of all the elements present in an array.

    In the program below, we will return the sum value from the user-defined function to the main function.

    And you can see that, unlike the above example where we declared the function static, here function is non-static which means we need an object reference of the class to access a non-static function. Object obj is created as an instance of ArrayToFunc class.

    using System;
    
    namespace Arrays
    {
       class ArrayToFunc
       {
          int getSum(int[] arr, int size)
          {
             int i;
             int sum = 0;
    
             for (i = 0; i < size; ++i)
             {
                sum += arr[i];
             }
    
             return sum;
          }
    
          static void Main(string[] args)
          {
             ArrayToFunc obj = new ArrayToFunc();
    
             //ceating and initializing array
             int[] arr = new int[] { 10, 20, 30, 40, 50 };
             int result;
    
             //Passing array to a function and
             //storing the returned value in a result variable
             result = obj.getSum(arr, 5);
    
             //Display
             Console.WriteLine("Sum of all the elements: {0} ", result);
          }
       }
    }

    Output:

    Sum of all the elements: 150