Fundamentals of C#

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:

  • A variable name can begin with an upper case or a lower case letter. The name can contain letters, digits and the underscore character (_).
  • The first character of the variable name must be a letter and not a digit. The underscore is also a legal first character, but it is not recommended at the beginning of a name.
  • C# is a case-sensitive language; hence the variable names "count" and "Count" refer to two separate variables.
  • C# keywords cannot be used as variable names. If you still need to use a C# keyword then prefix it with the '@' symbol.

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:

  • Object
  • String
  • Class
  • Delegate
  • Interface
  • Array

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

  • The standard out stream displays the output on the monitor.
  • In C#, all console operations are handled by the console class of the system namespace. A namespace is a collection of classes having similar functionalities.
  • To write data on the console, you need the standard output stream. This stream is provided by the output methods of console class. There are two output methods that write to the standard stream. They are:

    Console.Write (): Writes any type of data.

    Console.WriteLine (): Writes any type of data this data ends with a new line character in the standard output stream. This means any data after this line will appear on the new line.

Standard Output Method

2. Standard input method

  • The standard in stream takes the input and passes it to the console application for processing.
  • In C#, to read data, you need the standard input stream. This stream is provided by the input methods of the console class. These are two input methods that enable the software to take in the input from the standard input stream. These methods are:

    Console.Read (): Reads a single character.

    Console.ReadLine (): Read a line of strings.

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:

  • Selection or conditional Statements
  • Loop Statements
  • Jump Statements in C#

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: 

  • If construct
  • If..else construct
  • If..else if construct
  • Nested if construct
  • Switch.. case construct

Conditional Statement

1. If construct or statements

  • The if statement allows you to execute a block of statements after evaluating the specified logical condition.  The if statement starts with the if keyword and is followed by the condition. If the condition evaluates to true then the block of statements following the if statement is executed. If the condition evaluates to false then the block of statements following the if statements is ignored and the statement after the block is executed.
  • If a statement is followed by only one statement then it is not required to include the statement in curly braces.

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

  • The nested if construct consists of multiple if statements. The nested if construct starts with the if statement, that is called the outer if statements, and contains multiple if statements, that are called inner if statements.
  • In the nested if construct, the outer if condition controls the execution of the inner if statements. The compiler executes the inner if statements only if the condition in the outer if statements is true. In addition, each inner if statement is executed only if the condition in its previous inner if statement is true.

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.

  • Switch: The switch keyword is followed by an integer expression enclosed in parentheses. The expression must be of type int, char, byte, or short. The switch statement executes the case corresponding to the expression.
  • Case: The case keyword is followed by a unique integer constant and a colon. Thus, the case statement cannot contain a variable. The lock following a specific case value match. each case block must end with the break keyword that passes the control out of the switch construct.
  • Break: The break statement is optional and is used inside the switch .. case statement to terminate the execution of the statement sequence. The control is transferred to the statement after the end of switch. If there is no break then execution flows sequentially into the next case statement. Sometimes, multiple cases can be present without break statements between them.
  • Default: if no case value matches the switch expression value then the program control is transferred to the default block. This is the equivalent of the "else" of the if..else if construct.

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

  • The while loop is used to execute a block of code repetitively as long as the condition of the loop remains true. The while loop consists of the while statement, that begins with the while keyword followed by a Boolean condition. If the condition evaluates to true then the block of statements after the while statement is executed.
  • After each iteration, the control is transferred back to the while statement and the condition is checked again for another round of execution. When the condition is evaluated to false, the block of statements following the while statement is ignored and the statement appearing after the block is executed by the compiler.
  • The condition for the while loop is always checked before executing the loop. Therefore, the while loop is also referred to as the pre-test 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

  • The do-while loop is similar to the while loop; however, it is always executed at least once without the condition being checked. The loop starts with the do keyword and is followed by a block of executable statements. The while statement along with the condition appears at the end of this block.
  • The statements in the do-while loop are executed as long as the specified condition remains true. When the condition evaluates to false, the block of statements after the do keyword are ignored and the immediate statement after the while statement is executed.
  • The statements defined in the do-while loop are executed for the first time and then the specified condition is checked. Therefore, the do-while loop is referred to as the post-test 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

  • The nested for loop consists of multiple for statements. When one for loop is enclosed inside another for loop, the loops are said to be nested. The for loop that encloses the other for loop is referred to as the inner for loop.
  • The outer for loop determines the number of times the inner for loop will be invoked. For each iteration of the outer for loop, the inner for loop executes all its iterations.

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

  • A Foreach loop iterates through the items in the collection
  • The elements of a collection cannot be modified.
  • The foreach loop navigates through each value in the specified list and executes the block of statements for each value. The number of values in the list determines how many times the foreach loop will be executed. Each value in the list is referred to as an element. The foreach loop starts with the foreach statements that allows you to specify the identifier that holds a list of values.
  • While executing the foreach loop, all the elements specified in the for statement become read-only. Therefore, you cannot change the value of any element during the execution of 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

  • The goto statement allows you to directly execute a labeled statement or a ladeled block of statements. A labaled is an identifier ending with a colon. A single labeled block can be reffered by more than one goto statements.
  • The goto statement is denoted by the goto keyword.
  • You cannot use the goto statement for moving inside a block under the for, while or do-while loops.

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

  • Statements are referred to as logical grouping of variables, operators and C# keywords that perform a specific task. For example, the line that initializes a variable by assigning it a value is a statement.
  • In C#, a statement ends with a semicolon. A program is built with multiple statements and these statements are grouped in blocks. A block is a code consisting of related statements enclosed in curly braces. For example, the set of statements included in the main() method of a C# code is a block.
  • A method in C# is equivalent to a function in earlier programming languages such as C and  C++.

    Statement

  • Statements are used to specify the input, the process and the output takes of a program. Statements can consist of:
    • Data types
    • Variables
    • Operators
    • Constants
    • Literals
    • Keywords
    • Escape sequence characters
  • Statements help you build a logical flow in the program. with the help of statements, you can:
  • Initialize variables and objects
  • Take the input
  • Call a method of a class
  • Perform calculations
  • Display the output

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:

  • Produce values.
  • Produce a result from an evaluation.
  • From part of anther expression or a statement.

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

  • Arrays are reference type variables whose creation involves two steps: declaration and memory allocation.
  • An array declaration specifies the type of data that it can hold and identifier. This identifier is basically an array name and is used with a subscript to retrieve or set the data value at that location. Declaring an array does not allocate memory to the array.

Declaration Array

Initializing Arrays

  • An array can be created using the new keyword and then initialized. Alternatively, an array can be initialized at the time of declaration itself, in which case the new keyword is not used. Creating and initializing an array with the new keyword involves specifying the size of array. The number of elements stored in an array depends upon the specified size. The new keyword allocates memory to the array and values can be assigned to the array.
  • If the elements are not explicitly assigned then default values are stored in the array. The table shown alongside lists the default values for some of the widely used data types.

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

  • The elements of a single-dimensional array are stored in a single row in the allocated memory. The declaration and initialization of single-dimensional arrays are the same as the standard declaration and initialization of arrays.
  • In a single-dimensional array, the elements are indexed from 0 to (n-1), where n is the total number of elements in the array. For example, an array of 5 elements will have the elments indexed from 0 to 4 such that the first element is indexed 0 and the last element is indexed

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

  • Consider a scenario where you need to store the roll number of 50 students and their marks in three exams. Using a single-dimensional array, you require two separate arrays for storing roll numbers and marks respectively. However, using a multi-dimension array, you just need one array to store both, roll numbers as well as marks.
  • A multi-dimensional array allows you to store combinations of values of a single type in two or more dimensions. The dimensions of the array are represented as rows and columns similar to the rows and columns of a Microsoft Excel sheet.
  • A multi-dimensional array can have a maximum of eight dimensions.

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

  • A jagged array is a multidimensional array where one of the specified dimensions can have varying sizes. Jagged arrays can have unequal number of columns for each row.
  • A jagged array is a multi-dimensional array and is referred to as an array of arrays. It consists of multiple arrays where the number of elements within each array can be different. Thus, rows of jagged arrays can have different number of columns.
  • A jagged array optimizes the memory utilization and performance because navigating and accessing elements in a jagged array is quicker as compared to other multi-dimensional arrays.
  •  For example, consider a class of 500 students where each student has opted for a different number of subjects. Here, you can create a jagged array because the number of subjects for each student varies.

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

  • Consider the payroll system of an organization. The gross salary of an employee is calculated and stored in a variable of float type. Currently, the output is shown as float values. The payrll department wants the salary amount as a whole number and thus wants any digits after the decimal point of the calculated salary to be ignored. The programmer is able to do this using the typecasting feature of C#. Typecasting allows you to change the data type of a variable.
  • C# supports two types of casting, namely implicit and explicit. Type casting is mainly used to:
  • Convert a data type  to another data type belonging to the same or a different hierarchy. For example, the numaric hierarchy includes int, float and double. You can convert the char type into int type to display the ASCII value.
  • Display the exact numeric output. For example, you can display exact quotionts during mathematical divisions.
  • Prevent loss of numaric data if the resultant value exceeds the range of its variable's data type.

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

  • Implicit typecasting is done automatically by the compiler. The C# compiler automatically converts a lower precision data type into a higher precision data when the target variable is of a higher precision than the source variable.
  • The graphic illustrates the various data types and the data types of higher precision to which they can be converted.

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 is a process for converting a value type, like integer, to its reference type, like objects. This convertion is useful to reduce the overhead on the system during execution. This is because all value types are implicitly of object type.
  • To implement boxing, assign the value type to an object. While boxing, the variabe of the value type variable. This means that the object type has the copy of the value instead of its reference.
  • Boxing is done implicitly when a value type is provided instead of the expected reference type.

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 is a process for converting a reference type, like objects, to its value type, like integer. This conversion is useful to reduce the overhead on the system during execution. This is object type because all are implicitly of value types.
  • To implement unboxing, assign the reference type to an value type. While unboxing, the reference is of the reference type variable. This means that the value type has the copy of the value instead of its value.
  • Unboxing is done implicitly when a reference type is provided instead of the expected value type.

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();
        }
    }
}


Similar Articles