Category: CSharp Tutorial

  • C# Jagged Arrays

    Jagged Arrays are also known as “array of arrays” that is because the elements are arrays themselves. Their dimensions and sizes may be different.

    Declaration of jagged array in C#.

    Jagged array can be declared and created in a following way.

    //declaration
    int [][] marks;
    
    //creating to allocate memory
    int[][] marks = new int[5][];

    Initialization of Jagged array in C#

    As told above, a jagged array can be a different size. As the elements inside the arrays are the arrays themselves so they may vary in dimension. Let us see an example.

    You can initialize array in different ways, one of which is:

    //Initializing in single line
    int[][] marks = new int[2][]{
                   new int[]{88,90,60},
                   new int[]{45,80,55,92}
                 };

    As you can see, we initialize it in a single line with a new operator for each array element with a different dimension. One has 3 integers while the other have 4 integers.

    You can also separately initialize them with index number such as:

    marks[0] = new int[3] { 88,90,60 };         
    marks[1] = new int[4] { 45,80,55,92 };  

    Let us understand with an example:


    C# program illustrates using a jagged array

    Nested for loop is used to traverse through jagged array.

    using System;
    
    namespace Arrays
    {
       class JaggedArrays
       {
          static void Main(string[] args)
          {
             //jagged arrays initialization
             int[][] arr = new int[][]
             {
                new int[]
                   { 0, 1 },
                   new int[]
                   { 2, 3 },
                   new int[]
                   { 4, 5 },
                   new int[]
                   { 6, 7 }
             };
    
             //displaying
             for (int i = 0; i < 4; i++)
                for (int j = 0; j < 2; j++)
                   Console.WriteLine("arr[{0}][{1}] = {2}", i, j, arr[i][j]);
    
          }
       }
    }

    Output:

    arr[0][0] = 0
    arr[0][1] = 1
    arr[1][0] = 2
    arr[1][1] = 3
    arr[2][0] = 4
    arr[2][1] = 5
    arr[3][0] = 6
    arr[3][1] = 7

  • C# Multidimensional Arrays

    C# allows multi-dimensional arrays. This could be of 2D or 3D (two-dimensional or three-dimensional) Array. These arrays are stored in the form of a table (with rows and columns) which is also known as a matrix.

    In C#, multidimensional array is also known as rectangular arrays.

    To declare an array of multi-dimensions, we need to use comma (,) inside the brackets []. Such as:

    //Two Dimensional array (2D)
    int arr[,];
    
    //Three Dimensional array (3D)
    int arr[, ,];

    Initialization of Multi Dimensional Array in C#

    We can initialize a Multi-Dimensional Array (two-dimensional or three-dimensional) in the following ways in C#.

    1. Initialization of two-dimensional array:

    2D array is the simplest of multi-dimensional array. It has rows and column like a table.

    The following is the 2 by 3 matrix array that is array with 2 rows and 3 columns.

    int [,] arr = new int [2,3] {
       {0, 1, 2} ,   
       {3, 4, 5}     
    };

    2. Initialization of three-dimensional array:

    int[,, ] arr= new int[2, 2, 3]
    {  {
    	{ 1, 2, 3 },
    	{ 4, 5, 6 }  },
       {
    	{ 7, 8, 9 },
    	{ 10, 11, 12} }
    };

    You can also declare and initialize multi-dimensional array in three different ways .

    //Method 1
    int[,] arr = new int[2,2]= { { 1, 2 }, { 3, 4 } };  
    
    //Method 2: Omitting the array size 
    int[,] arr = new int[,]{ { 1, 2 }, { 3, 4 } };  
    
    //Method 3 Omitting new operator
    int[,] arr = { { 1, 2 }, { 3, 4 } };

    Accessing two Dimensional array in C#

    Accessing 2d Array:

    Subscripts are used to access the 2D array element. It can be achieved by placing the particular index number within the two brackets [][] (that is the row index and column index). Such as:

    arr[2,3]; //accessing in 4D
    OR
    int val = arr[2,3]; // assigning the element to val

    Accessing 3d Array:

    Accessing a 3-dimensional array is also as same as a two-dimensional array, the only difference is that in a 3d array we have to specify 3 subscripts with a required index number.

    //Accessing 3D Array
    arr[2,1,1]; 

    Example of C# Multi Dimensional Array:

    Example: Two Dimensional Array in C#

    C# Program to display all elements in a 2D array. We need to use a nested loop in order to iterate through a multi-dimensional array.

    using System;
    
    namespace Arrays
    {
       class Program2D
       {
          static void Main(string[] args)
          {
             // array with 4 rows and 3 columns
             int[, ] arr = new int[4, 3]
             {
                { 0, 1, 2 },
                { 3, 4, 5 },
                { 6, 7, 8 },
                { 9, 10, 11 }
             };
    
             //displaying
             for (int i = 0; i < 4; i++)
             {
                for (int j = 0; j < 3; j++)
                {
                   Console.WriteLine("arr[{0},{1}] = {2}", i, j, arr[i, j]);
                }
             }
          }
       }
    }

    Output:

    arr[0,0] = 0
    arr[0,1] = 1
    arr[0,2] = 2
    arr[1,0] = 3
    arr[1,1] = 4
    arr[1,2] = 5
    arr[2,0] = 6
    arr[2,1] = 7
    arr[2,2] = 8
    arr[3,0] = 9
    arr[3,1] = 10
    arr[3,2] = 11

    Example: Three Dimensional Array in C#

    C# Program to display all elements in an 3D array

    using System;
    
    namespace Arrays
    {
       class Program3D
       {
          static void Main(string[] args)
          {
             // 3D array with 2,2,3 dimension
             int[,, ] arr = new int[2, 2, 3]
             {
                {
                   { 1, 2, 3 },
                   { 4, 5, 6 }
                },
                {
                   { 7, 8, 9 },
                   { 10, 11, 12 }
                }
             };
    
             //displaying
             for (int i = 0; i < 2; i++)
             {
                for (int j = 0; j < 2; j++)
                {
                   for (int k = 0; k < 3; k++)
                   {
                      Console.WriteLine("arr[{0},{1},{2}] = {3}", i, j, k, arr[i, j, k]);
                   }
                }
             }
          }
       }
    }

    Output:

    arr[0,0,0] = 1
    arr[0,0,1] = 2
    arr[0,0,2] = 3
    arr[0,1,0] = 4
    arr[0,1,1] = 5
    arr[0,1,2] = 6
    arr[1,0,0] = 7
    arr[1,0,1] = 8
    arr[1,0,2] = 9
    arr[1,1,0] = 10
    arr[1,1,1] = 11
    arr[1,1,2] = 12

    As we saw the examples of 2D and 3D arrays, in a similar we can create any number dimension as required. However, the most used multidimensional array is a two-dimensional array.


  • C# Arrays

    You must have learned C, C++, Java, etc and like any other programming language, an array in C# is also a group or a fixed-size sequential collection of data having the same data-type stored in a contiguous memory location.

    The are used to store multiple values in a single variable instead of creating multiple variable for each value. It is a simple data structure format where the primitive type of data such as int, char, double, float, etc are stored and accessed randomly through their index number such as array[0], array[1], etc.

    Elements are arranged inside the array with index numbers starting from zero as the first elements.

    There are 3 types of arrays in C#:

    1. Single Dimensional Array
    2. Multidimensional Array
    3. Jagged Array

    Arrays are objects in C# whose allocation of memory is done dynamically in a program. Since they are objects, we can use predefined functions in C# to find the size of an array.


    Declaration of array in C#

    For declaration of an array in C#, the user needs to specify the type of element and number of elements in an array. Below is the declaration of the single-dimensional Array.

    data-type array_name[arraySize];

    The data type must be a valid C# data type, a unique name must be specified to each array and the arraySize must be of an integer constant. Let see an example for an integer array with 20 elements.

    int arr[20];

    Initialization of array in C#

    Declaration doe not mean that the array is initialized in a memory. Initialization of an array means assigning the value to an array.

    An array is a reference type that is it deals with the address of the elements. And since it is a reference type, we need to use new keyword in order to initialize the array variable.

    Syntax and Example:

    //syntax
    data-type [] <array_name> = new <data-type>[size];
    
    //Example
    int[] numbers = new int[10];

    This way an instance of an array is created with a new keyword.

    You can initialize an array in various ways as follows:

    1. Create and initialize an array.

    int[] num = new int[5]  {12,  88, 4, 32, 48};

    2. Omit the size of array.

    int[] num = new int[] {12,  88, 4, 32, 48}; 

    3. Initialize an array at the time of declaration.

    int[] num= {12,  88, 4, 32, 48}; 

    Initialize the array after multiple array declaration. Example:

    // Declaration of multiple integer array 
    int[] num1, num2;
    
    
    // Initialization of arrays
    num1 = new int[5] {12,  88, 4, 32, 48};
    
    num2 = new int[5] {14,  45, 6, 64, 99};

    Accessing Array Elements in C#

    As told above, that each array elements are associated with specific number that is the index numbers.

    An array element can be accessed by using the specific index number. It can be achieved by placing the particular index number within the bracket []. Such as:

    //Accessing single-dimensional Array
    arr[3]; //the 4th element is accessed
    arr[7]; //the 8th element is accessed

    You can also assign the value by accessing each of the position through index number. Example:

    int[] num= new int[5];
    num[0] = 45; //assigning 45 to the 1st element
    num[2] = 34; //assigning 34 to the 3rd element

    C# program for initialization, declaration and accessing an array

    In the program below we will initialize an array by the user input that is we will take an element of array from the user input.

    using System;
    
    namespace Arrays 
    {
       class Program 
       {
          static void Main(string[] args) 
          {
             //declaration and initialization an array
             int[] arr = {5, 10, 15, 20, 25};
             
             //displaying an array.
             for (int i = 0; i < arr.Length; i++)  
            {  
                Console.WriteLine("Element[{0}] = {1}", i, arr[i]);  
            }  
          }
       }
    }

    Output:

    Element[0] = 5
    Element[1] = 10
    Element[2] = 15
    Element[3] = 20
    Element[4] = 25

    Example: C# array initializing an array by accessing an array with an index number.

    using System;
    
    namespace Arrays 
    {
       class Program 
       {
          static void Main(string[] args) 
          {
            //Array declaration
            int[] arr;
      
            //allocation of memory for 5 integers
            arr = new int[5];
            
            //Initialization of an array.
            arr[0] = 5;
            arr[1] = 10;
            arr[2] = 15;
            arr[3] = 20;
            arr[4] = 25;
            //5 elements, index starts from 0 so index is till 4
            
             //displaying an array.
            for (int i = 0; i < arr.Length; i++)  
               Console.WriteLine("Element[{0}] = {1}", i, arr[i]);  
              
          }
       }
    }

    Output:

    Element[0] = 5
    Element[1] = 10
    Element[2] = 15
    Element[3] = 20
    Element[4] = 25

    Using the foreach Loop

    We used for loop above to display an element of an array one by one. Now we will do the same with foreach loop in C#. Traversal using foreach loop

    using System;
    
    namespace Arrays 
    {
       class Program 
       {
          static void Main(string[] args) 
          {
             //creating and initializing an array
             int[] arr = {5, 10, 15, 20, 25}; 
       
            int j = 0;
            //traversing to display with foreach
            foreach (int i in arr)  
            {  
                Console.WriteLine("arr[{0}] = {1}", j, i);
                j++;
            }  
          }
       }
    }

    Output:

    arr[0] = 5
    arr[1] = 10
    arr[2] = 15
    arr[3] = 20
    arr[4] = 25

    C# Arrays in Detail

    here is more to the arrays in C#. The above understanding mostly for 2D arrays. Click on the topic below to learn in detail about arrays in C#.

    C# Multidimensional Arrays
    C# Jagged Arrays
    C# Passing Array to Function
    C# Params Array
    C# Array Class

  • C# Out Parameter

    This method is Passing Parameters by Output. Unlike other methods that return only a single value from the method, the Out Parameter can return multiple values from a function.

    They are similar to reference type, except the data are transferred out rather than into it. C# provide out keyword for the out parameter type.


    Example: C# Out Parameter

    using System;
    
    namespace Programs
    {
       class Swapping
       {
          // function (user-defined)
          public void valueFunc(out int val)
          {
             int temp = 20;
             val = temp;
          }
    
          //main method
          static void Main(string[] args)
          {
             Swapping swapObj = new Swapping();
    
             int a = 10;
    
             Console.WriteLine("Before calling a method, a: {0}", a);
    
             //calling funciton with out keyword
             swapObj.valueFunc(out a);
    
             Console.WriteLine("After method called, a: {0}", a);
    
          }
       }
    }

    Output:

    Before calling a method, a: 10
    After method called, a: 20

  • C# Call by Reference

    Here reference refers t the addresses but not the actual value. In this method, we pass the reference of the argument to the formal parameter. To pass the parameters in C#, we have a keyword called ref.

    It passes a reference to a memory location rather the actual value, so the changes made to this passed parameters are reflected o the main program that is their value can be modified permanently.


    Example: C# call by reference

    using System;
    
    namespace Programs
    {
       class Swapping
       {
          //swapping function (user-defined)
          public void swapFunc(ref int x, ref int y)
          {
             int temp;
    
             temp = x;
             x = y;
             y = temp;
          }
    
          //main method
          static void Main(string[] args)
          {
             Swapping swapObj = new Swapping();
    
             int a = 10, b = 20;
    
             Console.WriteLine("Before swapping, a: {0}", a);
             Console.WriteLine("Before swapping, b: {0}", b);
    
             //calling swap funciton with ref keyword
             swapObj.swapFunc(ref a, ref b);
    
             Console.WriteLine("\nAfter swapping, a: {0}", a);
             Console.WriteLine("After swapping, b: {0}", b);
    
          }
       }
    }

    Output:

    Before swapping, a: 10
    Before swapping, b: 20
    
    After swapping, a: 20
    After swapping, b: 10

    Unlike call by value (from the previous tutorial), the swapped value of a and b can be seen in the output above.


  • C# Call By Value

    This is passing parameters by Value. These value-type parameters in C# copy the actual parameters to the function (known as formal parameters) rather than referencing it.

    Whenever a method is called by passing value, a new storage location is created for each value parameter. The copies of these values are stored, hence the changes made in the formal parameter have no effect on the actual argument.


    Example: C# call by value

    using System;
    
    namespace Programs
    {
       class Swapping
       {
         	//swapping function (user-defined)
          public void swapFunc(int x, int y)
          {
             int temp;
    
             temp = x;
             x = y;
             y = temp;
          }
    
         	//main method
          static void Main(string[] args)
          {
             Swapping swapObj = new Swapping();
    
             int a = 10, b = 20;
    
             Console.WriteLine("Before swapping, a: {0}", a);
             Console.WriteLine("Before swapping, b: {0}", b);
    
            	//calling swap funciton by passing a and b
             swapObj.swapFunc(a, b);
    
             Console.WriteLine("\nAfter swapping, a: {0}", a);
             Console.WriteLine("After swapping, b: {0}", b);
    
          }
       }
    }

    Output:

    Before swapping, a: 10
    Before swapping, b: 20
    
    After swapping, a: 10
    After swapping, b: 20

    As you can see the value of a and b is not changed, even though the two value are swapped inside a function.


  • C# Methods

    A method refers to a block of code (or a group of statements) that performs a specific task. It takes some inputs, does some computation based on that input and returns the output. They are also known as functions.

    The use of function in a program helps in many ways such as reuse of code, Optimization of Code. The function is declared within the curly braces {}.

    Every C# program has at least one function which is always executed and that is the main function from where the execution of the program begins.

    In order to use a method in a program, you need to:

    • define a method
    • call a method

    Defining Methods in C#

    Defining a method means to write its structure with all of its components. Generally, the function is defined in following way in C#:

    <Access Specifier> <Return Type> <Method Name>(Parameter List) 
    {
       //Method Body
    }

    Followings are the list of component present in a method.

    • Access Specifier: It defines its visibility to the other class, which means it specifies the variables and methods accessibility in the program.
    • Return type: A function may return a value unless it is a void function, which does not return any type of value. return_type is a data type of the function. It could return arithmetic values (int, float, etc.), pointers, structures, etc.
    • Function name: Function name refers to identifiers through which function can be identified uniquely. It is a function’s name that is stated to function by following some naming rules.
    • Parameter list: Parameter is also referred to as Argument. We can pass the values through the parameter when the function is invoked. The parameter list refers to the type, order, and number of the parameters of a function
    • Function Body: The function body is enclosed within the curly braces’{}’. It defines the task of a method within the curly braces.

    Remember that you can also leave the parameter list empty if you are not passing any value to the function.


    Calling Methods in C#

    To call a method means to execute the method and to do that we need to write a function name by passing the values as parameters (if any) within the two parentheses () and semicolon.

    Following is the syntax t call a function.

    function_name( parameter_list );

    Example: C# example of method

    let us see an example in C# where we create an addition function and pass the value to add and return the result to the main function. We will see the use of defining and calling a method in C#.

    using System;  
    
    namespace MethodExam  
    {  
        class Program  
        {  
            //defining a method  
            public int addFunc(int x, int y) 
            {  
                return x+y;
            }  
            
            //main Function 
            static void Main(string[] args)  
            {  
                int result;
                
                // Creating Object 
                Program program = new Program();  
                
                // Calling Function 
                result = program.addFunc(5, 10);  
                Console.WriteLine("The result of addition: {0}", result);
            }  
        }  
    }
    //Output:
    
    The result of addition: 15

    Example:

    Let us see the use of Access Specifier in the C# program. The program below will have two classes and the method of one class can be accessed by another class by using the instance of the class. We need to use the public Access Specifier.

    using System;
    
    namespace MethodExample
    {
       //class1
       class Class1
       {
          // User defined function without return type  
          public int largestFunc(int num1, int num2) 
          {
             if (num1 > num2)
                return num1;
             else
                return num2;
          }
       }
    
       //class2
       class Class2
       {
          static void Main(string[] args)
          {
             int largest;
    
             // Creating Object 
             Class1 class1 = new Class1();
    
             // Calling Function 
             largest = class1.largestFunc(100, 80);
             Console.WriteLine("The largest of two number is: {0}", largest);
          }
       }
    }

    Output:

    The largest of two number is: 100

    How to pass Parameter in Methods?

    We need to pass the values to a method in order to calculate just like an example shown above, we can do that in three different ways in C#.

    • call by value
    • call by reference
    • out parameter

    We will got through each of them in next tutorial.


  • C# goto Statement

    The goto statement is a jump statement that allows the user in the program to jump the execution control to the other part of the program. When encountered in a program, it transfers the execution flow to the labeled statement. The label (tag) is used to spot the jump statement.

    NOTE: Although the use of goto is avoided in programming language because it makes it difficult to trace the control flow of a program, making the program hard to understand and hard to modify.

    goto statement Flowchart:

    goto statement in C
    goto statement

    Syntax of goto statement in C#:

    goto label;
    ....
    ....
    label: statement; //label to jump
    ....
    ....
    statements

    Example of C# goto Statement

    // use of goto statement
    using System;
    
    public class GotoStatement
    {
       static public void Main()
       {
          int selected = 3;
          switch (selected)
          {
             case 1:
                //this is the label
                first_case:
                   Console.WriteLine("case: 1");
                break;
    
             case 2:
                Console.WriteLine("case: 2");
                break;
    
             case 3:
                Console.WriteLine("case: 3");
    
                // transfer the flow to case 1
                goto first_case;
    
             default:
                Console.WriteLine("No match found");
                break;
          }
       }
    }

    Output:

    case: 3
    case: 1

  • C# continue Statement

    It is a loop control statement. It is used to continue the loop in the program. The use of continue inside a loop skips the remaining code and transfer the current flow of the execution to the beginning o the loop.

    In case of for loop, the continue statement causes the program to jump and pass the execution to the condition and update expression by skipping further statement. Whereas in the case of while and do…while loops, the continue statement passes the control to the conditional checking expression.

    continue statement Flowchart:

    Continue statement in java
    continue statement

    Syntax of continue statement in C#:

    //continue syntax
    continue;

    Example of C# continue Statement

    using System;
    
    public class ContinueStatement
    {
       public static void Main(string[] args)
       {
          for (int i = 1; i <= 10; i++)
          {
             if (i == 7)
             {
                // 7 is skipped and control passed to for loop
                continue;
             }
    
             Console.WriteLine("Value of i: {0}", i);
          }
       }
    }

    Output:

    Value of i: 1
    Value of i: 2
    Value of i: 3
    Value of i: 4
    Value of i: 5
    Value of i: 6
    Value of i: 8
    Value of i: 9
    Value of i: 10

    Example: C# continue program in nested loops

    using System;
    
    public class ContinueNested
    {
       public static void Main(string[] args)
       {
          //outer loop
          for (int i = 1; i <= 2; i++)
          {
             //inner loop
             for (int j = 1; j <= 2; j++)
             {
                if (i == 1 && j == 2)
                {
                    //skips when i=2 and j=2 and control goes to the outer loop
                   continue;
                }
    
                Console.WriteLine("i: {0}, j: {1}", i, j);
             }
          }
       }
    }

    Output:

    i: 1, j: 1
    i: 2, j: 1
    i: 2, j: 2

    In the above output, i: 1, j: 2 is skipped as the continue statement stopped the further execution after that and transferred the execution control to the beginning of the outer loop.


  • C# break Statement

    break statement in programming is used to come out of the loop or switch statements. It is a jump statement that breaks the control flow of the program and transfers the execution control after the loop.

    The use of break statements in nested loops terminates the inner loop and the control is transferred to the outer loop.

    break statement Flowchart:

    break statement

    Syntax of break statement in C#:

    //break syntax
    break;

    Example C# break Statement

    Use of break statement in a single loop in C#.

    using System;
    
    public class BreakStatement
    {
       public static void Main(string[] args)
       {
          for (int i = 1; i <= 10; i++)
          {
             if (i == 6)
             {
                //stops loop at 6th iteration
                break;
             }
    
             Console.WriteLine("Value of i: {0}", i);
          }
       }
    }

    Output:

    Value of i: 1
    Value of i: 2
    Value of i: 3
    Value of i: 4
    Value of i: 5

    Example: C# break statement with the nested loop.

    using System;
    
    public class BreakNested
    {
       public static void Main(string[] args)
       {
          for (int i = 1; i <= 2; i++)
          {
             for (int j = 1; j <= 2; j++)
             {
                // for i = 1 and j = 2 is skipped in the output
                if (i == 1 && j == 2)
                   break;
    
                Console.WriteLine("i: {0}, j: {1}", i, j);
             }
          }
       }
    }

    Output:

    i: 1, j: 1
    i: 2, j: 1
    i: 2, j: 2

    As you can see in the output that i = 1 and j = 2 is skipped. This is because the break statement breaks the inner loop for i = 1 and j = 2 and transfer the control to the outer loop and the rest iteration continues until the loop condition is satisfied.