Question 1: Variables and its Declaration

Answer

A variable is an entity whose value can keep changing. For example, the age of a student, the address of a faculty member and the salary of an employee are all examples of variables.

In C# a variable is a location in the computer's memory that is identified by a unique name and is used to store a value. The name of the variable is used to access and read the value stored in it. Various types of data such as a character, an integer or a string can be stored in variables. Based on the type of data that needs to be stored in a variable, variables can be assigned various data types.

Variable

In C#, memory is allocated to a variable at the time of its creation. When you are referring to a variable, you are actually referring to the value stored in that variable.

Value Type

Syntax The following syntax is used to declare variables in C#:

<Data type> <variable Name>;

Where:

Datatype: Is a valid data type in C#.

VariableName: Is a valid variable name.

The following syntax is used to initialize variables in C#:

<VariableName> = <value>;

=: Is the assignment operator used to assign values.

Value: Is the data that is stored in the variable.

Snippet and Example

The following snippet declares two variables, namely empNumber and empName.

int empNumber;

String empName;

The preceding lines declare an integer variable, empName, and a string variable, empName.

Memory is allocated to hold data in each variable.

Values can be assigned to variables using the assignment operator (=) as shown below.

empNumber=100;

empName="David Blake";

You can also assign a value to a variable upon creation, as shown below.

Int empNumber=100;

Variable Naming Rules

A variable needs to be declared before it can be referenced. You need to follow certain rules when declaring a variable:

Variable name

Declaration

In C#, you can declare multiple variables at the same time in the same way you declare a single variable. After declaring variables, you need to assign values to them. Assigning a value to a variable is called initialization. You can assign a value to a variable while declaring it or at a later time. The following code snippet demonstrates how to declare and initialize variables in C#.

Variable Declaration

Question 2: Constant and its Declaration.

Answer

A constant value cannot be changed at compile time and runtime.

Need For Constant

Consider code that calculates the area of a circle. To calculate the area of the circle, the value of PI, ARC, and RADIUS must be provided in the formula. The value of PI is a constant value. This value will remain unchanged irrespective of the value of the radius provided.

Similarly, constants in C# are fixed values assigned to identifiers that are not modified throughout the execution of the code. They are defined when you want to preserve values to reuse them later or to prevent any modification to the values.

Constant

In C#, you can declare constants for all data types. You need to initialize a constant at the time of its declaration. Constants are declared for value types rather than for reference types. To declare an identifier as a constant, the const keyword is used in the identifier declaration. The compiler can identify constants at the time of compilation because of the const keyword.

Constant Declaration

Constant Declaration

Question 3: Data Types

Answer

You can store various types of values, such as numbers, characters or strings in different variables. But the compiler must know what kind of data a specific variable is expected to store. To identify the type of data that can be stored in a variable, C# provides many data types. When a variable is declared, a data type is assigned to the variable. This allows the variable to store values of the assigned data type. In the C# programming language, data types are divided into two categories. These are:

Data Type

1. Value Types

Variables of value types store actual values. These values are stored in a stack. The values can be either of a built-in data type or a user-defined data type. Most of the built-in data types are value types. The value type built-in data types are int, float, double, char and bool. Stack storage results in faster memory allocation to variables of value types.

Value Type

2. Reference Types

Variables of reference type store the memory address of other variables in a heap. These values can either belong to a built-in data type that is a reference type. Most of the user-defined data types such as class are reference types.

Classification

Reference data types store the memory reference of other variables. These other variables hold the actual values. Reference types can be classified as:

Reference Type

Object

Object is a built-in reference data type. It is a base class for all predefined and user-defined data types. A class is a logical structure that represents a real world entity. This means that the predefined and user-defined data types are created based on the Object class.

String

String is a built-in reference type. A String type signifies Unicode character string values. Once strings are created, they cannot be modified.

Class

A class is a user-defined structure that contains variables and methods. For example, the Employee class can be a user-defined structure that can contain variables such as empSalary, empName, and CalculateSalary (), that return the net salary of an employee.

Delegate

A delegate is a user-defined reference type that stores the reference of one or more methods.

Interface

An interface is a type of user-defined class for multiple inheritances.

Array

An array is a user-defined data structure that contains values of the same data type, such as marks as marks of students.

Question 4: Using Literals

Answer

A literal is a static value assigned to variables and constants. You can define literals for any data type of C #. Numeric literals might be suffixed with a letter to indicate the data type of the literal. This letter can be either in upper or lower case. For example, in the following declaration, string bookName = "Csharp", Csharp is a literal assigned to the variable bookName of type string.

In C#, there are six types of literals. These are:

  1. Boolean Literal
  2. Integer Literal
  3. Real Literal
  4. Character Literal
  5. String Literal
  6. Null Literal

1. Boolean Literal

Boolean literals two values, true or false. For example:

bool val=true;

Where, true: Is a Boolean assigned to the variable val.

2. Integer Literal

An integer literal can be assigned to an int, unit, long or ulong data types. A suffix for integer literals includes U, L, UL, or LU. U denotes unit or ulong, L denotes long. UL and LU denote ulong. For Example:

long val = 53L;

Where, 53L: Is an integer literal assigned to the variable val.

3. Real Literal

A real literal is assigned to float, double (default), and decimal data types.This is indicated by the suffix letter appearing after the assigned value. A real literal can be suffixed by F, D, or M. F denotes float, D denotes double and M denotes decimal. For example:

float val = 1.66F;

Where, 1.66F: Is a real literal assigned to the variable val.

4. Character Literal

A character literal is assigned to a char data type. A character literal is always enclosed in single quotes. For example:

Char val = 'A';

Where, A: Is a character literal assigned to the variable val.

5. String Literal

There are two types of string literals in C#, regular and verbatim. A regular string literal is a standard string. A verbatim string literal is similar to a regular string literal but is prefixed by the @ character. A string literal is always enclosed in double quotes. For example:

String mailDomain = "@gmail.com";

Where, @gmail.com: Is a verbatim string literal.

6. Null Literal

The null literal has only one value, null. For example:

String email = null;

Where, null: Specifies that email does not refer to any objects (reference)

Question 5: Keywords

Answer

Keywords are reversed words and are separately compiled by the compiler. They convey a predefined meaning to the compiler and hence cannot be created or modified. For example, int is a keyword that specifies that the variable is of data type integer. You cannot use keywords as variable names, method names or class names unless you prefix the keywords with the "@" character. The graphic lists the keywords used in C#:

Keyword

Question 6: Escape Sequence

Answer

An escape sequence character is a special character that is prefixed by a backslash (\). Escape sequence characters are used to implement special non-printing character such as a new line, a single space or a backspace. This non-printing character is used while displaying formatted output to the user to maximize readability. The backslash character tells the compiler that the following character denotes a non-printing character. For example, \n is used to insert a new line similar to the Enter key of the keyboard. There are multiple escape sequence characters in C# that are used for various kinds of formatting. The table shown below displays the escape sequence characters and their corresponding non-printing characters in C#.

Escape Sequence

Question 7: Console Operation

Answer

Console operations are tasks performed on the command line interface using executable commands. The console operations are used in software applications because these operations are easily controlled by the operating system. This is because console operations are dependent on the input and output devices of the computer system.

A console application is one that performs operations at the command prompt. All console applications consist of three streams, that are a series of bytes. These streams are attached to the input and output devices of the computer system and they handle the input and output operations. The three streams are:

1. Standard Output method

Standard Output Method

2. Standard input method

DEMO For ReadMethod

namespace ReadMethod
{
    class Program
    {
        static void Main(string[] args)
        {
            string Name;
            Console.Write("Enter your Name:-");
            Name = Console.ReadLine();
            Console.WriteLine("Your Name is:-" + Name);
            Console.WriteLine("Yoyr Name is:- {0}", Name);
            Console.ReadLine();
        }
    }
} 

3. Standard err method

The standard err stream display messages on the monitor.

4. Placeholders

The WriteLine ( ) and Write ( ) methods accept a list of parameters to format text before displaying the output. The first parameter is a string containing markers in braces to indicate the potion where the values of the variables will be substituted. Each marker indicates a zero-based index based on the number of variables in the list. For example, to indicate the first parameter position, you write {0}, second you write {1} and so on. The numbers in the curly brackets are called placeholders.

DEMO For Placeholder

namespace Placeholder
{
    class Program
    {
        static void Main(string[] args)
        {
            int Result, Number;
            Number = 5;
            Result = 100 * Number;
            Console.WriteLine("The result is " + Result + " when 100 is multiply by" + Number);
            Console.Write("The result is " + Result);
            Console.WriteLine(" when 100 is multiply by " + Number);
            Console.WriteLine("The result is {0} when 100 is multiply by {1}", Result, Number);
            Console.ReadLine();
        }
    }
}

5. Convert Methods

The ReadLine () method can be used to accept integer values from the user. The data is accepted as a string and then converted into the int data type. C# provides a convert class base data type.

Convert Method

DEMO For ConvertMethod

namespace ConvrtMethod
{
    class Program
    {
        static void Main(string[] args)
        {
            string Name;
            int Age;
            double Salary;
            Console.Write("Enter Your Name:-");
            Name = Console.ReadLine();
            Console.Write("Enter your Age:-");
            Age = Convert.ToInt32(Console.ReadLine());
            Console.Write("Enter your Salary:-");
            Salary = Convert.ToDouble(Console.ReadLine());
            Console.WriteLine("\nName is :-" + Name);
            Console.WriteLine("Age is :-" + Age);
            Console.WriteLine("Salary is :-" + Salary);
            Console.ReadLine();
        }
    }
}

Question 8: Programming Constructs or Control-Flow Statement

Answer

Welcome to the module C# Programming Constructs. Construct help in building the flow of a program. They are used for performing specific actions depending on whether certain is satisfied repeatedly or can transfer the control to another block.

In this module, you will learn about:

Control Flow Statement

Question 9: Selection or Conditional Statements

Answer

A selection construct is a programming construct supported by C# that controls the flow of a program. It executes a specific block of statements based on a Boolean condition, that is an expression returning true or false. The selection constructs are referred to as decision-making constructs. Therefore, selection constructs allow you to take logical decisions about executing different blocks of a program to achieve the required logical output. C# supports the following decision-making constructs:

Conditional Statement

1. If construct or statements

If Statement FlowChart

Syntax

If Statement Syntax

Demo Program

namespace IF_Ststement
{
    class Program
    {
        static void Main(string[] args)
        {
            int No1, No2;
            Console.WriteLine("Enter Value one:-");
            No1 = Convert.ToInt32(Console.ReadLine());
            Console.WriteLine("Enter Value second:-");
            No2 = Convert.ToInt32(Console.ReadLine());
            if (No1 > No2)
            {
                Console.WriteLine("First Value is Big");
            }
            if (No1 < No2)
            {
                Console.WriteLine("Second Value is Big");
            }
            Console.ReadLine();
        }
    }
}

2. IF..Else Construct or Statements

The if statements executes a block of statements only if the specified condition is true. However, in some situations, it is required to define an action for a false condition. This is done using the if..else construct.

The if..else construct starts with the if block followed by an else block. The else block starts with the else keyword followed by a block of statements. If the condition specified in the if statement evaluates to false then the statements in the else block are executed.

If else Statement

Syntax

If else Statement Syntax

Demo Program

namespace IF._._.Else_Statements
{
    class Program
    {
        static void Main(string[] args)
        {
            int No;
            Console.WriteLine("Enter Any Number:-");
            No = Convert.ToInt32(Console.ReadLine());
            if (No > 0)
            {
                Console.WriteLine("Number is Positive");
            }
            else
            {
                Console.WriteLine("Number is Negative");
            }
            Console.ReadLine();
        }
    }
}

3. If..Else If Construct or Statements

The if..else if construct allows you to check multiple conditions and it executes a different block of code for each condition. This construct is also referred to as if..else if ladder. The construct starts with the if block followed by one or more else if blocks followed by an optional else block. The conditions specified in the if..else if construct are evaluated sequentially. The execution starts from the if statement. If a condition evaluates to false then the condition specified in the following else if statement is evaluated.

If else if Statement

Syntax

If else if Syntax

Demo Program

namespace IF._._ElseIF_Statement
{
    class Program
    {
        static void Main(string[] args)
        {
            int Num;
            Console.WriteLine("Enter Any Number:-");
            Num = Convert.ToInt32(Console.ReadLine());
            if (Num < 0)
            {
                Console.WriteLine("The Number is Negative");
            }
            else if (Num % 2 == 0)
            {
                Console.WriteLine("The Number is odd");
            }
            else
            {
                Console.WriteLine("The Number is even");
            }
            Console.ReadLine();
        }
    }
}

4. Nested If Construct or Statements

Nested If Statement

Syntax

Nested If Syntax

Demo Program

namespace Nested_IF_Statement
{
    class Program
    {
        static void Main(string[] args)
        {
            int Salary, Service;
            Console.Write("Enter Yrs Of Service:-");
            Service = Convert.ToInt32(Console.ReadLine());
            Console.Write("Enter Salary:-");
            Salary = Convert.ToInt32(Console.ReadLine());
            if (Service < 5)
            {
                if (Salary < 500)
                {
                    Console.WriteLine("Provided Bonus:-> 100");
                }
                else
                {
                    Console.WriteLine("Provided Bonus:-> 200");
                }
            }
            else
            {
                Console.WriteLine("Provided Bonus:-> 700");
            }
            Console.ReadLine();
        }
    }
}

5. Switch .. Case Construct or Statements

A program is difficult to comprehend when there are too many if statements representing multiple selection constructs. To avoid using multiple if statements, in certain cases the switch .. case statement can be used as an alternative.

The switch .. case statement is used when a variable needs to be compared against different values.

Syntax

Switch Case Statement

Demo Program

namespace Switch_Case
{
    class Program
    {
        static void Main(string[] args)
        {
            int Day;
            Console.WriteLine("Enter Your Choice:-");
            Day = Convert.ToInt32(Console.ReadLine());
            switch (Day)
            {
                case 1:
                    Console.WriteLine("Sunday");
                    break;
                case 2:
                    Console.WriteLine("Monday");
                    break;
                case 3:
                    Console.WriteLine("Tuesday");
                    break;
                case 4:
                    Console.WriteLine("Wednesday");
                    break;
                case 5:
                    Console.WriteLine("Thursday");
                    break;
                case 6:
                    Console.WriteLine("Friday");
                    break;
                case 7:
                    Console.WriteLine("Saturday");
                    break;
                default:
                    Console.WriteLine("Enter a Number between 1 to 7");
                    break;
            }
            Console.ReadLine();
        }
    }
}

Question 10: Loop Construct and Statements

Answer

Loops allow you to execute a single statements or a block of statements repeatedly. The most common uses of loops include displaying a series of numbers and tacking repetitive input. In software programming, a loop construct contains a condition that helps the compiler identify the number of times a specific block will be executed. If the condition is not specified then the loop continues infinitely and is called an infinite loop. The loop constructs are also referred to as iteration statements.

C# supports four types of loop constructs. These are:

  1. The while loop
  2. The do..while loop
  3. The for loop
  4. The foreach loop

1. The "While" Loop

While Statement

Syntax

While Statement

Demo Program

namespace While_Loop
{
    class Program
    {
        static void Main(string[] args)
        {
            int num = 1;
            //Console.Write("Enter Number:-");
            //num = Convert.ToInt32(Console.ReadLine());
            while (num <= 11)
            {
                if ((num % 2) == 0)
                {
                    Console.WriteLine(+num);
                }
                num = num + 1;
            }
            Console.ReadLine();
        }
    }
}

2. The "Do-While" Loop

Do While Statement

Syntax

Do While Syntax

Demo Program

namespace DO_While_Loop
{
    class Program
    {
        static void Main(string[] args)
        {
            int num;
            Console.Write("Enter Number:-");
            num = Convert.ToInt32(Console.ReadLine());
            do
            {
                if ((num % 2) == 0)
                {
                    Console.WriteLine(+num);
                }
                num = num + 1;
            } while (num <= 11);
            Console.ReadLine();
        }
    }
}

3. The "for" Loop

The for statement is similar to the while statement in its function. The statements within the body of the loop are executed as long as the condition is true. Here too, the condition is checked before the statements are executed.

For Statement

Syntax

For Statement Syntax

Demo Program

namespace For_Loop
{
    class Program
    {
        static void Main(string[] args)
        {
            int num, i;
            Console.Write("Enter Number:-");
            num = Convert.ToInt32(Console.ReadLine());
            for (i = num; i <= 11; i++)
            {
                if ((i % 2) == 0)
                {
                    Console.WriteLine(+i);
                }
            }
            Console.ReadLine();
        }
    }
}

4. Nested "for" Loop

Nested For Statement

Demo Program

namespace Nested_For_Loop
{
    class Program
    {
        static void Main(string[] args)
        {
            int i, j;
            for (i = 0; i < 5; i++)
            {
                for (j = 0; j < 2; j++)
                {
                    Console.WriteLine("Welcome To CCSIT");
                }
            }
            Console.ReadLine();
        }
    }
}

5. The "foreach" Loop

ForEach Statement

Syntax

ForEach Syntax

Demo Program

namespace foreach_Loop
{
    class Program
    {
        static void Main(string[] args)
        {
            // FOREACH LOOP IS USE FOR STRING
            string[] Names = { "joy", "Mariya", "Jeni", "Wilson" };
            Console.WriteLine("Employee Name");
            foreach (string person in Names)
            {
                Console.WriteLine("{0}", person);
            }
            // FOREACH LOOP IS USE FOR INTEGER
            int[] No = { 1, 2, 3, 4 };
            Console.WriteLine("\nEmployee Number");
            foreach (int Number in No)
            {
                Console.WriteLine("{0}", Number);
            }
            Console.ReadLine();
        }
    }
}

Question 11: Jump Statements

Answer

Jump statements are used to transfer control from one point in a program to another. There will be situations where you need to exit out of a loop prematurely and continue with the program. In such cases, jump statements are used. A Jump statement unconditionally transfers control of a program to a different location. The location to which a jump statement transfers control is called the target of the jump statement.

C# supports four types of jump statements. These are:

  1. Break
  2. Continue
  3. Goto
  4. Return

1. Break Statement

The break statement is used in the selection and loop constructs. It is most widely used in the switch .. case construct and in the for and while loops. The break statement is denoted by the break keyword. In the switch .. case construct, it is used to terminate the execution of the construct. In this case, the control passes to the next statement following the loop.

Syntax

Jump Statement

Demo Program

namespace Break_Statement
{
    class Program
    {
        static void Main(string[] args)
        {
            int i;
            double no, sum = 0, avg;
            Console.WriteLine("Enter Number One by One:-");
            Console.WriteLine("Enter Zero to stop Entry");
            for (i = 1; i <= 1000; i++)
            {
                no = Convert.ToDouble(Console.ReadLine());
                if (no == 0)
                {
                    break;
                }
                sum = sum + no;
            }
            Console.WriteLine("Sum =>" + sum);
            Console.ReadLine();
        }
    }
}

2. The "continue" Statement

The continue statement is most widely used in loop constructs. This statement is denoted by the continue keyword. The continue statement is used to end the current iteration of the loop and transfer the program control returns back to the beginning of the loop. The statements of the loop following the continue statement are ignored in the current iteration.

Continue Statement

Demo Program

namespace Continue_Statement
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Even numbers in the range of 1-10");
            for (int i = 1; i <= 10; i++)
            {
                if (i % 2 != 0)
                {
                    continue;
                }
                Console.Write(i + "\n");
            }
            Console.ReadLine();
        }
    }
}

3. The "goto" Statement

Goto Statement

Demo Program

namespace Goto_Statement
{
    class Program
    {
        static void Main(string[] args)
        {
            int i = 0;
        display:
            Console.WriteLine("Hello Word");
            i++;
            if (i < 5)
            {
                goto display;
            }
        }
    }
}

4. The "return" Statement

The return statement returns a value of an expression or transfers control to the method from which the currently executing method was invoked. The return statement is denoted by the return keyword. The return statement must be the last statement in the method block.

Return Statement

Demo Program

namespace Return_Statement
{
    class Program
    {
        static void Main(string[] args)
        {
            int YrsofService = 5;
            double salary = 1250;
            double bonus = 0;
            if (YrsofService <= 5)
            {
                bonus = 50;
                return;
            }
            else
            {
                bonus = salary * 0.2;
            }
            Console.WriteLine("Salary amount:" + salary);
            Console.WriteLine("Bonus amount:" + bonus);
            Console.ReadLine();
        }
    }
}

Question 12: Statements

Answer

Example of Statements

Statement Example

Types of Statements

C# statements are similar to statements in C and C++. C# statements are classified into seven categories depending on the function they perform. These categories are the following.

Selection statements

A selection statement is a decision-making statement that checks whether a specific condition is true or false. The keyword associated with this statement are: if, else, switch and case.

Iteration statements

An iteration statement helps you to repeatedly execute a block of code. The keywords with this statement are: do, for, foreach, and while.

Jump statements

A jump statement helps you transfer the flow from one block to another block in the program. The keywords associated with this statement are: break, continue, default, goto, return.

Exception handling statements

An exception handling statement manages unexpected situations that hinder the normal execution of the program. For example, if the code is dividing a number by zero, the program will not execute properly. To avoid this situation, you can use the following exception handling statements: throw, try-catch, try-finally and try-catch-finally.

Checked and unchecked statements

The checked and unchecked statements manage arithmetic overflows. An arithmetic overflow occurs if the resultant value is greater than the range of the target variable's data type. The checked statement halts the execution of the program whereas the unchecked statement assigns junk data to the target variable. The keywords associated with these statements are: checked and unchecked.

Fixed statement

The fixed statement is required to tell the garbage collector not to move that object during execution. The keywords associated with this statement are: fixed and unsafe.

Lock statement

A lock statement in locking the critical code blocks. This ensures that no locking the critical code. These statements ensure security and only work with reference statements ensure security and only work with reference types. The keyword associated with this statement is: - lock.

Question 13: Expressions

Answer

Expressions are used to manipulation data. Like in mathematics, expressions in programming languages, including C#, are constructed from the operands and operators. An expression statement in C# ends with a semicolon (;).

Expressions are used to:

Expression

Question 14: Difference between Statements andExpressions

Answer

Statement and Expression

Question 15: Introduction to Arrays

Answer

An array is a collection of related data with similar data types.

Consider a program that stores the names of 100 students. To store the names, the programmer would create 100 variables of the string type.

Creating and managing these 100 variables is very difficult but the programmer can create an array for storing the 100 names.

An array is a collection of related values placed in a contiguous memory location and these values are referred to using a common array name. This simplifies the maintanance of these values.

Array

An array always stores values of a single data type. Each value is referred to as an element. These elements are accessed using subscripts or index numbers that determine the position of the element in the array list.

C# supports zero-based index values in an array. This means that the first array element has index number zero while the last element has index number n-1, where n stands for the total number of elements in the array.

This arrangement of sorting values helps in efficient storage of data, easy sorting of data and easy tracking of the data length.

Define Array

Declaration of array

Declaration Array

Initializing Arrays

Initialize Array

Syntax

Array Syntax

Demo Program

namespace Simple_Array
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] count = new int[10];
            int counter = 0, i;
            for (i = 0; i < 10; i++)
            {
                count[i] = counter++;
                Console.WriteLine("The Count value is:-" + count[i]);
            }
            Console.ReadLine();
        }
    }
}

Types of Arrays

C# .Net mainly has three types of arrays, these are:

  1. Single-Dimension Array.
  2. Multi-Dimension Array.

1. Single-Dimension Array

Single Dimention Array

Syntax

Single Dimention Array Syntax

Demo Program

namespace Simple_Array
{
    class Program
    {
        static void Main(string[] args)
        {
            string[] students = new string[3] { "Jems", "Alex", "Joy" };
            int i;
            for (i = 0; i < students.Length; i++)
            {
                Console.WriteLine(students[i]);
            }
            Console.ReadLine();
        }
    }
}

2. Multi-Dimension Array

There are two types of multi-dimensional array, these are:

1. Rectangular Array.

2. Jagged Array.

Multi Dimention Array

1. Rectangular Array

A rectangular array is a multi-dimensional array where all the specified dimensions have constant values. A rectangular array will always have the same number of columns for each row.

Syntax

Rectangular Array Syntax

Demo Program

namespace Multi_Dimensional_array
{
    class Program
    {
        static void Main(string[] args)
        {
            int[,] dimension = new int[4, 5];
            int numOne = 0;
            for (int i = 0; i < 3; i++)
            {
                for (int j = 0; j < 3; j++)
                {
                    dimension[i, j] = numOne;
                    numOne++;
                }
            }
            for (int i = 0; i < 3; i++)
            {
                for (int j = 0; j < 3; j++)
                {
                    Console.Write(dimension[i, j] + " ");
                }
                Console.WriteLine();
            }
            Console.ReadLine();
        }
    }
}

2. Jagged Array

Jagged Array

Demo Program

namespace Jagged_Arrays
{
    class Program
    {
        static void Main(string[] args)
        {
            string[][] companies = new string[3][];
            companies[0] = new string[] { "Intel", "AMD" };
            companies[1] = new string[] { "IBM", "Microsoft", "Sun" };
            companies[2] = new string[] { "HP", "Canon", "Lexmark", "Epson" };
            for (int i = 0; i < companies.GetLength(0); i++)
            {
                Console.Write("List of companies in group" + (i + 1) + ":\t");
                for (int j = 0; j < companies[i].GetLength(0); j++)
                {
                    Console.Write(companies[i][j] + " ");
                }
                Console.WriteLine();
            }
            Console.ReadLine();
        }
    }
}

3. Using the "foreach"Loop for Arrays

The foreach loop in C# is anextension of the for loop. This loop is used to perform specific actions on collections, such as arrays. The loop reads every element in the specified array and allows you to execute a block of code for each element in the array. This is particularly useful for reference types, such as strings.

ForEach Statement

Syntax

ForEach Syntax

Demo Program

namespace Foreach_Loop_For_Array
{
    class Program
    {
        static void Main(string[] args)
        {
            string[] studentNames = new string[3] { "JAY", "MAHESH", "RAJ" };
            foreach (string studName in studentNames)
            {
                Console.WriteLine("Congratulations!! " + studName + " You Have Selected for This Job");
            }
            Console.ReadLine();
        }
    }
}

Question 16: Type Casting

Answer

Type Casting

1. Implicit Conversions for C# Data Types

Implicit typecasting refers to an automatic conversion of data types. This is done by the C# compiler. Implicitly typecasting is done only when the destination and source data types belong to the same hierarchy. In addition, the destination data type must hold a larger range of values than the source data type. Implicit conversion prevents the loss of data as the destination data type is always larger than the source data type. For example, if you have a value of int type then you can assign that value to the variable of long type.

Conversion

Snippet

Conversion Syntax

Demo Program

namespace Implicit_TypeCasting
{
    class Program
    {
        static void Main(string[] args)
        {
            int valOne = 20;
            int valTwo = 30;
            float valThree;
            valThree = valOne + valTwo;
            Console.WriteLine("Addition of Two variables:-" + valThree);
            Console.ReadLine();
        }
    }
}

Rules

Rules

2. Explicit Conversions for C# Data Types

Explicit typecasting refers to changing a data type of higher precision into a data type of lower precision. For example, using explicit type casting, you can manually convert the value of float type into int type. This typecasting might result in loss of data. This is because when you convert the float data type into the int data type, the digits after the decimal point are lost.

Explicit Conversion

Syntax

Explicit Conversion Syntax

Demo Program

namespace Implicit_Typecasting
{
    class Program
    {
        static void Main(string[] args)
        {
            float side = 10.5F;
            int area;
            area = (int)(side * side);
            Console.WriteLine("Area of the Squre = {0}", area);
            Console.ReadLine();
        }
    }
}

Question 17: Boxing and Unboxing

Answer

Boxing and unboxing are concepts of C# data type system. Using these concepts, a value of any value type can be converted to a reference type and a value of any refeerance type can be converted to a value type.

Boxing

Boxing

Syntax

Boxing Syntax

Demo Program

namespace Boxing_Type
{
    class Program
    {
        static void Main(string[] args)
        {
            // Demo-1
            int radious = 10;
            double area;
            area = 3.14 * radious * radious;
            object boxed = area;
            Console.WriteLine("DEMO-1 OUTPUT\n");
            Console.WriteLine("Area of the circule= {0}\n", area);
            //Demo-2
            double bonus = 0.0;
            double salary;
            Console.WriteLine("DEMO-2 OUTPUT\n");
            Console.WriteLine("Enter Salary:-");
            salary = Convert.ToDouble(Console.ReadLine());
            bonus = salary * 0.1;
            object any = bonus;
            Console.WriteLine("Bonus of Rs.{0} is Rs.{1}", salary, bonus);
            Console.ReadLine();
        }
    }
}

Unboxing

UnBoxing

Syntax

UnBoxing Syntax

Demo Program

namespace UnBoxing_Type
{
    class Program
    {
        static void Main(string[] args)
        {
            //Demo-1
            int length = 10;
            int breadth = 20;
            int area;
            area = length * breadth;
            object boxed = area;
            int num = (int)boxed;
            Console.WriteLine("DEMO-1 OUTPUT\n");
            Console.WriteLine("Area of the Rectangle={0}\n", num);

            //Demo-2
            double bonus = 0.0;
            double salary;
            Console.WriteLine("DEMO-2 OUTPUT\n");
            Console.WriteLine("Enter Salary:-");
            salary = Convert.ToDouble(Console.ReadLine());
            bonus = salary * 0.1;
            object any = bonus;
            double num2 = (double)bonus;
            Console.WriteLine("Bonus of Rs.{0} is Rs.{1}", salary, bonus);
            Console.ReadLine();
        }
    }
}