dotnet tech lounge

115
.NET TECH LOUNGE Table of Contents Module 1 (.Net) Module 2 (User Interface) 1. Introduction to User Interface and HTML 2. CSS ( Cascading Style Sheets ) 3. JavaScript

Upload: kalyani-khuspe

Post on 22-Nov-2015

215 views

Category:

Documents


77 download

TRANSCRIPT

  • .NET TECH LOUNGE Table of Contents

    Module 1 (.Net)

    Module 2 (User Interface)

    1. Introduction to User Interface and HTML

    2. CSS ( Cascading Style Sheets ) 3. JavaScript

  • Module 1

    Introduction to .NET

    The objective of this course is understand about .Net.

    Please go through below video which guides you through on each module in .Net Lounge:

    https://www.youtube.com/watch?v=Rm79Rl429NA

    1. Application Understanding

    Objective

    Introduction to Application Understanding

    Different types of Applications

    Examples of each type of applications

    IT applications are all about managing information using a technology. To Create, Read, Update

    and Delete information are some of the main operations in all IT applications. Login, Search,

    Validations etc are some common functionalities in all IT applications. For

    example http://irctc.com/displayServlet is a web application and you can check all operations and

    functionalities in this website. Three Tier Architecture is the common architecture used in modern

    IT applications. Presentation, Business Logic and Database will be in three different physical

    entities.

    Different types of Applications

    Desktop Application is a computer software designed to help the user to perform specific

    tasks. Eg: VLC Media Player, Microsoft Office.

    Web Application - is an application that is accessed over a network such as the Internet or an

    Intranet. Eg: www.Amazon.com, www.facebook.com.

    Mobile Application - Mobile application software is developed for small low-power handheld

    devices such as personal digital assistants, enterprise digital assistants or mobile phones. Eg:

    Weather Forcast, News Reader, Games, Whatsapp etc.

  • Related Videos

    https://www.youtube.com/watch?v=yGogBKK9Sn8

    2. Problem Solving Orientation

    Objective

    Introduction to Problem Solving Approach

    Identifying a problem

    Step-by-step approach to solve a problem

    Key elements required for problem solving and programming

    2.1. Problem solving orientation

    What is a problem??

    A problem is a difficulty or a challenge, or situation that needs a solution.

    Eg: Driving a car, Making Tea, Solving a crossword puzzle

    Sample problem scenario

    We can discuss a problem scenario faced by Railway department.

  • As part of service and development in nation lots of trains were added to the Railway

    department. As a result the passenger services also increased. Railway stations increased.

    Lakhs of passengers and customers started availing various services like regular ticket bookings,

    reservation of tickets, ticket cancellations, enquires etc. Services for passengers and customers

    at railway stations resulted in long queues. This created unhappy passengers and customers.

    Railway employees were also overburdened with paper and manual work. Dissatisfied customers

    and overburdened employees was the end result of development.

    Railway wants to improve stake holder satisfaction. This was the problem scenario faced by

    Railway department. This problem can be solved in 2 ways manually or automated.

    Railway department hired new staff and increased the number of customer service counters.

    Passenger count and train services are steadily increasing, so this solution is not going to work

    for a long term. Manual errors are also creeping up during calculations, leading to customer

    dissatisfaction, and wastage of time to correct errors.

    Management is now thinking why not automate the entire system.

    Ticket booking and seat availability tracking

    Passenger data management

    Regular ticketing and so on

    They decided to come up with a computerized system that handles various day to day activities

    at their office.

    Computer Programs

    Computer is a machine. It needs to be instructed how to perform a task, how to handle data,

    where to store it and so on.

    Programs Set of instructions that is carried out by the computer

    Software Collection of computer programs and data that tells computer what to do

    In a computer based solution, business requirement of a user, ultimately get translated to lines of

    code that instructs computer to work in such a way as to meet the requirement

    How to solve a problem

  • Whenever a problem occurs, people tend to concentrate too much on the solution and

    sometimes forget the essence of the problem. It is essential for the individual to have a right

    approach to the problem itself in order to figure out the best solution.

    People who are really good at solving problems go about it systematically. They have a way of

    placing the problem in context and do not jump to conclusions. They evaluate all alternatives.

    Steps in Problem Solving

    Step 1 - Analyzing the problem

    This involves understanding the input and output, various alternatives to reach the output, listing

    the assumptions

    Step 2 - Designing an algorithm

    Defining a step by step procedure to solve the problem

    Step 3 - Testing the design for correctness

    Checking for the correctness of algorithm by walking through the algorithm manually

    Step 4 - Implementing the solution (Translating to code)

    Once the correctness of algorithm is checked, it can be translated to any programming language

    Step 5 - Testing the program

    Once the program is developed it needs to be tested against various test cases which checks if

    the program is correct for all expected range of inputs.

    Step 6 Deployment and Maintenance

    In this module, the product or the output is given to the customer or end user for their purpose.

  • Related Videos

    https://www.youtube.com/watch?v=lzW7S55P1Gc

    2.2. Key elements required for problem solving and programming

    1. Good analytical skills

    2. Declarative and imperative knowledge about the solution

    3. Ability to apply abstraction

    4. Knowledge in a programming language

    5. Following good programming practices

    1. Good analytical skills

    Analytical skill is the ability to use good reasoning in analyzing a situation and also the ability to

    solve the problem. Analytical skill can also be said as the ability to organise a mass of data and

    draw proper correlations, and then interpreting these trends in terms that are meaningful to

    others.

    Suppose you have rain data for your town for the past thirty years, given to you at random, with

    no comments. You can organise the data chronologically, then draw a graph to demonstrate the

    data and then , by extending the graph along its closest fitting curve, you can make reasonable

    predictions about the extent of rain next year, assuming that all other factors remain STEADY.

    2. Declarative and imperative knowledge about the solution

    Declarative knowledge is the knowledge of what to do and imperative knowledge is the

    knowledge of how to do. If you have problem in hand and when you know the solution of the

    problem then you have declarative knowledge. So What is type of knowledge is called

    declarative knowledge. Imperative knowledge is a procedural knowledge which is the knowledge

    exercised in the performance of some task. How to type of knowledge is called Imperative

    Knowledge.

  • Example:

    Declarative Knowledge:

    This What is type of knowledge is called Declarative knowledge

    Imperative Knowledge:

    This How to Knowledge is called Imperative Knowledge.

  • 3. Ability to apply abstraction

    Abstraction will modularize the logic for a specific functionality in a computer program. It will also

    hide complexity of implementation details of a function behind a specific interface defined to

    invoke the function. It is recommended that programmers use abstractions whenever suitable in

    order to avoid duplication.

    4. Knowledge in a programming language

    A programming language is a formal language designed to communicate instructions to a

    machine, particularly a computer. Programming languages can be used to create programs that

    control the behaviour of a machine and/or to express algorithms precisely.

    Elements of a programming language

    1. Syntax: structural elements of the language. Programs must be syntactically correct.

    2. Grammar: defines how syntactical elements need to be combined to form programs

    3. Semantics: defines meaning of the code

    5. Good programming practices

    A good programming practice is related to writing efficient and readable code, a code which is

    easily maintainable.

    Related Videos

    https://www.youtube.com/watch?v=jtuqZxClqKs

    3. C# Introduction

    3.1. .net and C#

    We can use Visual Studio to create Console, Windows and web applications. Different

    programming languages like C#,VB,VC++ and J# can be used to develop applications. Here we

    will learn how C# can be used in Visual Studio 2010 Express Edition to create console

    applications. Express edition will give you all basics options to code, debug and run applications

  • using C#. This series features Visual C# 2010 Express Edition however the content will be valid

    no matter what edition or version of Visual Studio you have.

    Get Visual Studio Express Edition

    If you dont already have some edition of Visual Studio installed you can use the link below to get

    a free copy of Visual C# 2010 Express Edition.

    http://www.visualstudio.com/en-us/downloads#d-2010-express

    Follow the instructions in the website to install Visual Studio Express Edition 2010 in your

    machine. You may need to register it if you want to use it for more than 30 days. The C# express

    supports Console/Windows applications. Web developer Express is required for ASP.Net Web

    Applications.

    Quick Overview of Visual C# Express Edition IDE

    After installing it you can go to All Programs and click on Microsoft Visual C# 2010 Express as

    shown below.

  • In Visual Studio you can select File->New Project or New Project link below Microsoft Visual C#

    2010 Express logo as shown below.

    In Visual Studio you can select File?New Project or New Project link below Microsoft Visual C#

    2010 Express logo as shown below.

  • When you click on OK you will get an editor as shown below.

    If you want see all files in the solution Click on solution explorer as shown below.

    Static void main() function is the starting point of all C# programs.

    Related Videos

    https://www.youtube.com/watch?v=TgWrRSinbEY

  • 4. C# Declaring and Assigning Variables

    Objective

    Understand variables and DataTypes

    Understand variable Definition and Initialization

    Understand arrays

    Understand array Definition and Initialization

    4.1. C# - Data types

    What is a variable?

    A variable is nothing but a name given to a storage area that our programs can manipulate.

    Each variable in C# has a specific type, which determines the size and layout of the variable's

    memory, the range of values that can be stored within that memory, and the set of operations

    that can be applied to the variable.

    The basic value types provided in C# can be categorized as:

    In C#, variables are categorized into the following types:

    Value types

    Reference types

    Value Types

    Value type variables can be assigned a value directly. They are derived from the

    class System.ValueType.

    The value types directly contain data. Some examples are int, char, float, which stores numbers,

    alphabets, floating point numbers, respectively. When you declare an int type, the system

  • allocates memory to store the value.

    The following table lists the available value types in C# 2010:

    To get the exact size of a type or a variable on a particular platform, you can use the sizeof

    method. The expression sizeof(type) yields the storage size of the object or type in bytes.

    Following is an example to get the size of int type on any machine:

    namespace DataTypeApplication

    {

    class Program

    {

    static void Main(string[] args)

    {

    Console.WriteLine("Size of int: {0}", sizeof(int));

    Console.ReadLine();

    }

    }

    }

    When the above code is compiled and executed, it produces the following result:

    Size of int: 4

    Reference Types

    The reference types do not contain the actual data stored in a variable, but they contain a

    reference to the variables.

    In other words, they refer to a memory location. More than one variable can point to the same

    memory location, the reference types can refer to a memory location. If the data in the memory

    location is changed by one of the variables, the other variable automatically reflects this change

    in value. Example of built-in reference types are: object and string.

    Object Type

    The Object Type is the ultimate base class for all data types in C# Common Type System (CTS).

  • Object is an alias for System.Object class. So object types can be assigned values of any other

    types, value types, reference types, predefined or user-defined types.

    Example:

    object obj;

    obj = 100;

    obj = "Tom";

    String Type

    The String Type allows you to assign any string values to a variable. The string type is an alias

    for the System.String class. It is derived from object type. The value for a string type can be

    assigned using string literals as

    String str = "Tutorials Point";

    The user-defined reference types are: class, interface, or delegate, which shall be discussed

    later.

    4.2. Variable Definition & Initialization in C#

    Syntax for variable definition in C# is:

    ;

    Here, data_type must be a valid C# data type including char, int, float, double, or any user-

    defined data type, etc., and variable_list may consist of one or more identifier names separated

    by commas.

    Some valid variable definitions are shown here:

    int i, j, k;

    char c, ch;

    float f, salary;

    double d;

    Variable Initialization in C#

    Variables are initialized (assigned a value) with an equal sign followed by a constant expression.

    The general form of initialization is:

  • variable_name = value;

    Variables can be initialized (assigned an initial value) in their declaration. The initializer consists

    of an equal sign followed by a constant expression as:

    = value;

    Some examples are:

    int d = 3, f = 5; /* initializing d and f. */

    byte z = 22; /* initializes z. */

    double pi = 3.14159; /* declares an approximation of pi. */

    char x = 'x'; /* the variable x has the value 'x'. */

    It is a good programming practice to initialize variables properly, otherwise program would

    produce unexpected result.

    Try the following example which makes use of various types of variables:

    namespace VariableDefinition

    {

    class Program

    {

    static void Main(string[] args)

    {

    short a;

    int b ;

    double c;

    /* actual initialization */

    a = 10;

    b = 20;

    c = a + b;

    Console.WriteLine("a = {0}, b = {1}, c = {2}", a, b, c);

    Console.ReadLine();

    }

    }

  • }

    When the above code is compiled and executed, it produces the following result:

    a = 10, b = 20, c = 30

    4.3. Accepting Values from User

    The Console class in the System namespace provides a function ReadLine() for accepting input

    from the user and store it into a variable.

    For example,

    int num;

    num = Convert.ToInt32(Console.ReadLIne());

    The function Convert.ToInt32() converts the data entered by the user to int data type, because

    Console.ReadLine() accepts the data in string format.

    The program below prompts the user to enter his name and he's given a welcome message with

    his name:

    namespace WelcomeProgram

    {

    class Program

    {

    static void Main(string[] args)

    {

    string name;

    Console.Write("Hello, please enter your name: ");

    name = Console.ReadLine();

    Console.WriteLine("Welcome " + name);

    }

    }

    }

  • 4.4. Arrays

    An array stores a fixed-size sequential collection of elements of the same type. An array is used

    to store a collection of data, but it is often more useful to think of an array as a collection of

    variables of the same type.

    Instead of declaring individual variables, such as number0, number1, ..., and number99, you

    declare one array variable such as numbers and use numbers[0], numbers[1], and ...,

    numbers[99] to represent individual variables. A specific element in an array is accessed by an

    index.

    All arrays consist of contiguous memory locations. The lowest address corresponds to the first

    element and the highest address to the last element.

    Declaring Arrays

    To declare an array in C#, you can use the following syntax:

    datatype[] arrayName;

    where,

    datatype is used to specify the type of elements to be stored in the array.

    [ ] specifies the rank of the array. The rank specifies the size of the array.

    arrayName specifies the name of the array.

    For example,

    double[] balance;

    Initializing an Array

    Declaring an array does not initialize the array in the memory. When the array variable is

    initialized, you can assign values to the array.

    Array is a reference type, so you need to use the new keyword to create an instance of the array.

    For example,

    double[] balance = new double[10];

    Assigning Values to an Array

    You can assign values to individual array elements, by using the index number, like:

  • double[] balance = new double[10];

    balance[0] = 4500.0;

    You can assign values to the array at the time of declaration, like:

    double[] balance = { 2340.0, 4523.69, 3421.0};

    You can also create and initialize an array, like:

    int [] marks = new int[5] { 99, 98, 92, 97, 95};

    In the preceding case, you may also omit the size of the array, like:

    int [] marks = new int[] { 99, 98, 92, 97, 95};

    You can also copy an array variable into another target array variable. In that case, both the

    target and source would point to the same memory location:

    int [] marks = new int[] { 99, 98, 92, 97, 95};

    int[] score = marks;

    When you create an array, C# compiler implicitly initializes each array element to a default value

    depending on the array type. For example for an int array all elements would be initialized to 0.

    Related Videos

    https://www.youtube.com/watch?v=GuO11WN1AFU

    https://www.youtube.com/watch?v=lc-6RrVfsno

  • 5. C# -Conditional Operators

    Objective

    Understand conditional constructs, boolean operations and expressions, logical operators

    and precedence

    Perform simple, nested and complex conditional operations

    Ability to choose right conditional constructs

    5.1. Introduction

    There are many scenarios in our everyday life, where we need to take some decisions based on

    some criteria or condition. Decision making is one of the major parts of .Net also.

    Conditional logic is involved when different operations are to be performed based on whether a

    decision is true or not. Conditional expressions consists of conditions that results in a boolean

    value and performs actions based on the boolean result. There are three types of decision

    making statements in c#. They are:

    1. if ...then This statement is the most basic of all control flow statements. If then statement has

    a certain condition expression. It executes a certain section of code only if that particular

    condition is true. If the condition is false, control jumps to the end of the if then statement.

    2. If ... then ... else This statement provides a secondary path of execution when the condition

    becomes false. There can be nested if then else statement also.

    3. switch case A switch statement allows a variable to be tested for equality against a list of

    values. Each value is called a case, and the variable being input is checked for each case. This

  • statement helps to select one out of the many choices based on an integer or character value.

    The conditions will accept only a value and not a range/comparison. The syntax is different from

    if else statements. Here we are comparing the input value with different cases. We can set a

    default case for inputs which do not satisfy any case.

    The following rules apply to a switch statement:

    1. The variable used in a switch statement can only be a simple datatype like string, int, char etc.

    2. You can have any number of case statements within a switch. Each case is followed by the

    value to be compared to and a colon. Every case is terminated by a break statement.

    3. The value for a case must be the same data type as the variable in the switch and it must be a

    constant or a literal.

    4. When the variable is found equal to a case, the statements following that case will execute

    until a break statement is reached. When a break statement is reached, the switch terminates,

    and the flow of control jumps to the next line following the switch statement.

    A switch statement can have an optional default case, which must appear at the end of the

    switch. The default case can be used for performing a task when none of the cases is true.

    Ternary Operator and If Else Statement

    We have already discussed ternary operator in previous course. This operator can be considered

    as the short hand of if then else statement.

    Syntax

    result = (someCondition) ? value1 : value2

    This means,

    someCondition is executed.

    If the outcome of someCondition is true, assign the value of value1 to result,

    else assign the value of value2 to result

    Example

    static void Main(String[] args)

    {

    Console.WriteLine("Enter two numbers");

  • int num1 = Convert.ToInt16(Console.ReadLine());

    int num2 = Convert.ToInt16(Console.ReadLine());

    int comparisonResult = (num1 > num2) ? num1 : num2;

    Console.WriteLine(comparisonResult);

    Console.ReadKey();

    }

    Thus we can conclude the ternary operator can be considered as the short hand of if then else

    statement.

    5.2. Conditional (Logical) Operators

    Conditional (Logical) Operators are used to evaluate a condition that's applied to one or two

    boolean expressions. The result of the evaluation is either true or false.

    There are 2 conditional operators:

    && the logical AND operator.

    || the logical OR operator

    The logical AND and logical OR operators both take two operands. Each operand is a boolean

    expression (i.e., it evaluates to either true or false).

    The logical AND condition returns true if both operands are true, otherwise it returns false.

    Syntax

    (condition1 && condition2) // will return true if both conditions are true

    Example:

    static void Main(String[] args)

    {

    Console.WriteLine("Enter three numbers");

    int num1 = Convert.ToInt16(Console.ReadLine());

    int num2 = Convert.ToInt16(Console.ReadLine());

    int num3 = Convert.ToInt16(Console.ReadLine());

    int result = 0;

  • if ((num1 >= num2) && (num1 >= num3))

    result = num1;

    else if ((num2 >= num1) && (num2 >= num3))

    result = num2;

    else

    result = num3;

    Console.WriteLine(result);

    Console.ReadKey();

    }

    The logical OR condition returns false if both operands are false, otherwise it returns true.

    Syntax

    (condition1 || condition2) // will return true if at least one condition is true

    Examples:

    static void Main(String[] args)

    {

    Console.WriteLine("Enter three numbers");

    int num1 = Convert.ToInt16(Console.ReadLine());

    int num2 = Convert.ToInt16(Console.ReadLine());

    int num3 = Convert.ToInt16(Console.ReadLine());

    string result = "failure";

    if ((num1 == 0) || (num2 == 0) || (num3 == 0))

    result = "success";

    Console.WriteLine(result);

    Console.ReadKey();

    }

    Related Videos

    https://www.youtube.com/watch?v=Eu9shw-rjFE

    https://www.youtube.com/watch?v=byHHD8vXZoE

  • 5.3. Practice Problems

    1. Two numbers, num1 and num2 are input. Find whether num1 is greater, num2 is greater or

    both are equal.

    Our solution should have a method which input 2 numbers, compared the numbers and returns

    the result of comparison. Here we have to use a conditional statement.

    Solution:

    class Program

    {

    static void Main(String[] args)

    {

    Console.WriteLine("Enter two numbers");

    int num1 = Convert.ToInt16(Console.ReadLine());

    int num2 = Convert.ToInt16(Console.ReadLine());

    if (num1 > num2)

    {

    Console.WriteLine(num1 + " is greater than " + num2);

    }

    else if (num1 == num2)

    {

    Console.WriteLine(num1 + " is equal to " + num2);

    }

    else

    {

    Console.WriteLine(num2 + " is greater than " + num1);

    }

    Console.ReadKey();

    }

    }

    Input : 5, 3

  • 13, 5

    15,15

    Output :

    5 is greater than 3

    13 is greater than 5

    15 is equal to 15

    Here we have used the conditional statements to compare the 2 numbers using relational

    operators. Based on the result of the condition the result is constructed as a string statement with

    the numbers appended to for a meaningful statement. The result is printed.

    2. Two numbers, num1 and num2 are input to the program. Based on the users choice one of the

    arithmetic operation (add, subtract, multiply, divide) should happen.

    Here we can use the switch case as decision maker. This can be implemented in if else also, but

    we need to write more than 4 else cases. Instead a switch case can be used. Consider 1 - Add, 2

    - Subtract, 3 - Multiply, 4 Divide. Pass the 2 numbers and the operator to the program. Write a

    switch case which will accept the operator number and decide which operation to do. Then

    based on the decision made it will do the operation and assign the result. Break is used to break

    one particular case after its execution. Break will bring the control at the end of switch case.

    Default should be written so that, if the user enters a number other than 1,2,3 or 4 then it should

    enter default and give a relevant message.

    Solution:

    class Program

    {

    static void Main(String[] args)

    {

    Console.WriteLine("Enter two numbers");

    int num1 = Convert.ToInt16(Console.ReadLine());

    int num2 = Convert.ToInt16(Console.ReadLine());

  • Console.WriteLine("Enter the operation:\n1.

    Add\n2.Subtract\n3.Multiply\n4.Divide");

    int operate = Convert.ToInt16(Console.ReadLine());

    int result = 0;

    switch (operate)

    {

    case 1:

    Console.WriteLine("Addition");

    result = num1 + num2;

    break;

    case 2:

    Console.WriteLine("Subtraction");

    result = num1 - num2;

    break;

    case 3:

    Console.WriteLine("Multiplication");

    result = num1 * num2;

    break;

    case 4:

    Console.WriteLine("Division");

    result = num1 / num2;

    break;

    default:

    Console.WriteLine("Invalid operation");

    result = 0;

    break;

    }

    Console.WriteLine("Result : " + result);

    Console.ReadKey();

    }

    }

  • Input : 10,2,1

    Output : 12

    6. C#- Basic Iterations (Loops)

    Objective

    Understand iterations and loops

    Understand and implement solutions involving simple and nested iterations

    Understand iterator, state, counter and accumulator

    Understand finite, infinite loops

    Understand break and continue conditions

    6.1. Loops

    There may be a situation when we need to execute a block of code several number of times, and

    is often referred to as a loop.

    C# has three looping mechanisms. They are:

    1. while Loop

    2. do...while Loop

    3. for Loop

    While loop:

    In the example a while loop is written to print the numbers from 0 to 5. The variable x is initialized

    with 0. Then in while loop, x is checked whether the value is less than 6. If the value of x is less

    than 6, it enters the loop and prints the value of x. Then we increment the value of x by 1. Again it

  • comes to while condition and checks the condition. While condition will be true until x = 5. When

    x = 6, the loop exits.

    static void Main(string[] args)

    {

    int x = 1;

    while (x < 6)

    {

    Console.WriteLine("x is " + x);

    x = x + 1;

    }

    Console.WriteLine("Exit testWhileLoop");

    Console.ReadLine();

    }

    Output:

    x is 1

    x is 2

    x is 3

    x is 4

    x is 5

    Exit testwhileLoop

    Note:

    You can check the sample solution to know the implementation of code in Visual Studio

    https://s3.amazonaws.com/cc-uploads/Sample1.zip

    Do ... While loop:

    The do while construct consists of a block of code and a condition. First the code within the block

    is executed, and then the condition is evaluated. If the condition is true the block is executed

    again, this repeats until the condition turns false.

    do

    {

    statements

  • }

    while (condition);

    The example given for while is restructured in do while loop. The output is same.

    static void Main(String[] args)

    {

    int x = 1;

    do

    {

    Console.WriteLine("x is " + x);

    x = x + 1;

    } while (x < 6);

    Console.WriteLine("Exit testDoWhileLoop");

    Console.ReadLine();

    }

    Output:

    x is 1

    x is 2

    x is 3

    x is 4

    x is 5

    Exit testDoWhileLoop

    Note:

    You can check the sample solution to know the implementation of code in Visual Studio

    https://s3.amazonaws.com/cc-uploads/Sample2.zip

    See the same example with the value of x = 6, here we can see the difference of while and do

    while loops. Here we can see the condition x< 6 is giving false as x = 6. But since its do while

  • loop, the statements get executed first. So we get xis 6 as output. Then it will check the condition

    and exit the loop. If it was while loop the condition is checked first and loop will be exited.

    static void Main(String[] args)

    {

    int x = 6;

    do

    {

    Console.WriteLine("x is " + x);

    x = x + 1;

    } while (x < 6);

    Console.WriteLine("Exit testDoWhileLoop");

    Console.ReadLine();

    }

    Output:

    x is 6

    Exit testDoWhileLoop

    Note:

    You can check the sample solution to know the implementation of code in Visual Studio

    https://s3.amazonaws.com/cc-uploads/Sample3.zip

    For loop:

    For loops are used when the number of iterations are known before entering the loop.

    Counter based for loops: for loops that work on the basis of a counter value. The start and end

    values of counter will be mentioned and loop will be executed as many times until the counter

    reaches the end value. The counter will be incremented/decremented during each iteration.

    for (initialization; termination; increment/decrement) { statement(s) }

    class Program

    {

    static void Main(string[] args)

    {

  • for (int x = 1; x < 6; x++)

    {

    Console.WriteLine("x is " + x);

    }

    Console.WriteLine("Exit testForLoop");

    Console.ReadLine();

    }

    }

    Output:

    x is 1

    x is 2

    x is 3

    x is 4

    x is 5

    Exit testForLoop

    Iterator based loops: This is commonly known as for-each loop. Some languages (E.g. Java,

    PHP,C#) has a for each loop that iterates through a collection of items. This type of for loop does

    not maintain an explicit counter.

    foreach(string s in stringList)

    {

    //do something to item

    }

    Finite and Infinite Loops

    Finite loops: Loops that terminate after a particular number of iterations based on either a

    counter value or event within the loop is known as finite loop.

    Infinite loops: A loop that do not terminate is known as infinite loop. Programmers should check

    for conditions or errors that might result in an infinite loop which is not expected during the

    execution of a program.

  • Some times infinite loops are used to make a program segment loop for ever until an exceptional

    conditional such as an error arises. Such loops created intentionally will usually have a control

    structure that controls termination of loop.

    Eg. An event driven program should loop for ever handling events as they occur only stopping

    when terminated by an operator.

    6.2. Break & Continue Keyword

    The break keyword is used to stop any conditional statement or loop. The break keyword must

    be used inside any loop or a switch statement. Break statement terminates a for, while or do

    while loop. The control is transferred to the first statement after the loop. The break keyword will

    stop the execution of the innermost loop and start executing the next line of code after the block.

    Syntax: break; (The syntax of a break is a single statement inside any loop)

    You have already used break in switch case in conditional operators. We can see an example

    where we use break in a loop. Here we have a for loop from 1 to 5. Also there is a break in the

    flow when value of x = 3. After the break happens, the flow jumps out of for loop and prints Exit

    testForLoop.

    static void Main(string[] args)

    {

    for (int x = 1; x < 6; x++) {

    if(x==3){

    Console.WriteLine("Breaking the loop");

    break;

    }

    Console.WriteLine("x is " + x);

    }

    Console.WriteLine("Exit testForLoop");

    Console.ReadLine();

    }

    Output:

  • x is 1

    x is 2

    Breaking the loop

    Exit testForLoop

    Continue Keyword

    The continue keyword can be used in any of the loop control structures. Continue statement

    skips the current iteration of a for, while or do while loop. It causes the loop to immediately jump

    to the next iteration of the loop.

    Syntax: continue; (The syntax of a continue is a single statement inside any loop)

    We can see an example where we use continue in a loop. Here we have a for loop from 1 to 5.

    Also there is a continue statement in the flow when value of x = 3. After the continue happens,

    the flow stops the execution of that iteration and jumps to the next iteration of the loop. See the

    output printed. Here when x = 3, the continue statement executes and skips rest of that iteration .

    So the value of x when x = =3 is not printed. This is because the print statement is below the

    continue. The continue statement will stop the current running iteration and starts the next

    iteration.

    static void Main(string[] args)

    {

    for (int x = 1; x < 6; x++)

    {

    if (x == 3)

    {

    Console.WriteLine("Continuing the loop");

    continue;

    }

    Console.WriteLine("x is " + x);

    }

  • Console.WriteLine("Exit testForLoop");

    Console.ReadLine();

    }

    Output:

    x is 1

    x is 2

    Continuing the loop

    x is 4

    x is 5

    Exit testForLoop

    Related Videos

    https://www.youtube.com/watch?v=_Q1HvBgzows

    https://www.youtube.com/watch?v=uErKDQpwjy0

    6.3. Practice Problems

    1. Find the even numbers below a given number.

    The requirement is to find and print all the even numbers present below a given number.

    The method should accept a number from the main. There should be a loop in the method, which

    will start from 1 and increment by 1. Each number need to be checked whether its an even

    number or not. If its an even number print the number else continue.

    Solution:

    static void Main(string[] args)

    {

    int input;

    Console.WriteLine("Enter the Number");

    input = Convert.ToInt32(Console.ReadLine());

  • for (int x = 1; x
  • 7.1. Evolution of Programming Approaches

    As we have seen in the previous course, for automating the solution of a problem, we need to do

    programming. There were different programming approaches which evolved based on

    requirements and better programming practices. In the beginning the programs will be small and

    simple. Later the programs will become more and more complex based on the requirements. So

    there is a need for better programming approaches.

    The following are the different programming approaches which evolved.

    Unstructured Programming

    Structured Programming

    Procedural Programming

    Modular Programming

    Object Oriented Programming

    Related Videos

    https://www.youtube.com/watch?v=8T1Mion6ilw

    7.2. Elements of Programming

    Data

    Programs are set of instructions that act upon data that is received (input) and transforms it into

    required information.

    Expressions

    Instructions that carry out required operations on the given data.

    Functions/Methods

    A block of instructions that accept some data, carry out some operations and returns an output.

    Structured Programming Approach

    Structured approach to programming, implements a system as a collection of functions that

    accepts data, processes it and returns an output. A function some times calls another function,

    when it wants to make use of the functionality defined in the other function.

    A program to calculate salary of an employee might look some what like this. A function to

  • calculate salary, calling another two functions that calculates HRA and DA. The values returned

    by these modules is added up in the module that calculates salary,

    In Structured programming the flow of program execution is based on the structure of the

    program written. There is more dependency between the variables and the program like a chain.

    Example : C language

    Object Oriented Programming Approach

    We write programs that make up a software to solve a problem in real world. In real world

    problem domains we do not find any functions that work on data. We find objects that are

    described by some state (data) and having some behaviours (functions).

    Object Oriented Approach to programming is about implementing a system as collection of

    objects that have state and behaviours, interacting with each other to achieve expected

    functionalities.

    Example: C++ & C#

    In OO programming, the program basic entity is object. An object is any real world entity that has

    a well-defined structure and behaviour. Eg: Pencil, Laptop, Mobile, Car, Book, and Human. Every

    object has its own characteristics. Every object has 5 sets of characteristics.

  • 7.3. Characteristics of an object

    An object is a real world entity that has a well-defined structure and behaviour. It typically

    processes the following characteristics:

    State

    Behaviour

    Responsibility

    Communication

    Identity

    State

    State of an object is a set of properties that describes the object, which can take different values

    during the life time of the object.

    Eg: Bob is an employee of tech smart, let us have a look into Bobs properties as an employee:

    Knowing Responsibility: It is the responsibility of an object to know its state

  • Behaviour

    Behaviour is how objects react to its state changes or any other operations performed on it

    A bank account can perform these responsibilities, by making use of state values or other data

    provided to it.

    Doing Responsibility: It is the responsibility of object to behave according the operations

    performed on it.

    Responsibility

    Doing responsibilities

    Doing something itself, like creating an object/doing a calculation

    Initiating action in other objects

    Controlling and coordinating activities in other objects

    Knowing responsibilities

    Knowing about state

    Knowing about related objects

    Knowing about things it can derive or calculate

    Communication

    Objects can communicate with each other, provided they know each other.

    Objects can respond to the message send by another object, by performing an action, or

    returning some data.

    Identifying objects and behaviours

    The nouns in the requirements specification would suggest the Objects in the problem domain.

    The verbs from the requirements specification would suggest object behaviours.

  • Related Videos

    https://www.youtube.com/watch?v=wE3t1NTlDlE

    8. C# - Classes and Objects

    Objective

    Introduction to Classes

    Data-Types

    Access Level Modifiers

    Object State - Properties

    Constructors

    OOP Concepts Encapsulation

    Main Method

    Sample Programs

    8.1. Introduction to Classes

    We know Class describes the state & behaviour of objects. Thus a Class decides/ defines what

    an object does and what data it holds. After creating/ designing a Class, any number of similar

    objects can be created.

    Thus, a class becomes the template for an object .An object becomes the instance of its class.

    How to write a C# Class

  • The syntax of the class is as follows:

    class ClassName

    {

    //code here

    }

    For e.g.; Suppose we have to create a class for Customer, then

    Class Customer

    {

    //code here;

    }

    Classes Properties, Get & Set

    The variables declared inside a Class are by default not accessible from other Classes, but to

    access the values from outside,properties are used.

    The properties are special methods called as Accessors, which allows the data to be assigned

    to/ accessed from the variable, through Read-only/ Write-only/ Read-Write permissions. The

    properties enable a class to expose only the getting & setting of values, while hiding the

    implementation of code.

    The syntax of the property is as follows:

    Accessmodifier datatype PropertyName

    {

    get { return variablename; }

    set { variablename= value; }

    }

    The property contains 2 blocks, a get block, which is called Get accessor & set block, which

    is called Set accessor. When the data has to be read using the property, the get accessor will

    work & when the data has to be assigned to, the set accessor will work.

  • Thus the property restricts the access to the value. Property containing only the get block/

    get accessor is a Read-Only Property. A property containing only the set block/ set accessor is

    the Write-Only property, the Property containing both the Get & Set Accessor is a Read-Write

    Property.

    For e.g.; we will include the properties for Id & name in our customer class. The Id of the

    customer is restricted from modification whereas the name can be given with Read-Write

    Permission. Our Class will look like as follows:

    class Customer

    {

    //Declaration of Variable

    private int _id=0 ;

    //Property for ID restricted from assigning new values

    public int ID

    {

    get { return _id; }

    }

    //Declare Variable for name & use Property for Read & Write

    private string _name;

    public string Name

    {

    get { return _name; }

    set { _name = value; }

    }

    }

    Related Videos

    https://www.youtube.com/watch?v=wk2SRUEvzzo

  • 8.2. Classes - Constructors

    Constructors help to pass the initial values to the variables declared in a class, during the

    creation of its object.

    In C#, the variables inside a class are initialized with default values using a constructor. A

    constructor should have the same name as that of the class. The initial values are passed as

    parameters.

    The Syntax of a Constructor is as follows:

    AccessModifier ClassName(datatype parameter1,datatype parameter2)

    {

    variable1 =parameter1;

    variable2 = parameter2;

    }

    Since the constructor needs to be accessed from other Classes, the Access modifier will always

    be public (most permissive).

    For e.g.; we can include a Constructor also in our class Customer, for initializing the Id and name

    of any customer. Now, our class will look like:

    class Customer

    {

    //Declaration of Variable

    private int _id = 0;

    //Property for ID restricted from assigning new values

    public int ID

    {

    get { return _id; }

    }

    //Declare Variable for name & use Property for Read & Write

    private string _name;

    public string Name

    {

  • get { return _name; }

    set { _name = value; }

    }

    //Constructor for passing the initial value(as parameter) to the variables

    public Customer(int id, string name)

    {

    //variable = parameter

    _id = id;

    _name = name;

    }

    }

    A class can have multiple constructors. Also, if a class does not contain a constructor, C# will

    instantiate the default values using a default Constructor.

    Encapsulation - OOPS Concept

    C# support object- Oriented Programming Approach, which include : Encapsulation, inheritance

    & Polymorphism.

    Encapsulation: A group of related members treated as a single unit. A Class is a single unit

    which keeps the variables, its related properties, constructors & other members inside it. Here

    the members are encapsulated within the Class.

    For e.g; our customer class holds some members. Using Encapsulation, all the members are

    treated as a single unit using the class name Customer.

    Related Videos

    https://www.youtube.com/watch?v=jwlSagZcPOk

    8.3. Object Creation and Initialization

    A class defines the type of object. So the object will have the type as the Class name. And the

    object is created using the new keyword followed by the constructor. The constructor is invoked

    by the new operator.

  • The syntax of creating an object using a default constructor for a Class with name ClassName, is

    as follows:

    ClassName objectName= new ClassName();

    Here, ClassName() - is used to invoke the default constructor.

    The syntax of creating an object with parameterized constructor is as follows:

    ClassName objectName = new ClassName(newValue);

    Here, ClassName(newValue) is used to invoke the parameterized Constructor taking only one

    value as the parameter and newValue represent the value to the variable initialised inside the

    Constructor.

    For e.g.; we will see how to create an object of our class customer, using a default Constructor:

    Customer customer= new Customer();

    Now, we will see how to create an object of our class customer using parametrized Constructor:

    Customer newCustomer = new Customer(100, Jack);

    Classes - Main Method

    In C#, Console Application or a Windows Application needs to have starting point for the

    program. The Main Method is defined as the entry point of a .exe program, i.e. the program

    starts execution from the Main Method.

    One class should contain a Main Method. Since the execution starts from the Main Method

    and it is invoked without creating an object of the Class, the Main method should be defined

    using the "static" keyword.

    Main method should also specify a return type. The return type can be either "void" type

    which means returns nothing or int datatype which means returns an integer value by the

    completion of Main method.

    Main Method can be defined with or without parameters. The Parameter are used to take the

    Command line Arguments and the parameters are defined using string[] args.

    The syntax of the Main Method can be given as follows:

  • static void Main()

    {

    //code here

    }

    or

    static void Main(string[] args)

    {

    //code here

    }

    Here we will see the Class program with the Main Method creating the objects of class customer

    and using the members defined inside.

    class Program

    {

    static void Main(string[] args)

    {

    Customer customer = new Customer();

    customer.Name="Joe";

    Console.WriteLine("{0} :: {1}", customer.ID, customer.Name);

    Customer newCustomer = new Customer(100, "Jack");

    Console.WriteLine("{0} :: {1}", newCustomer.ID, newCustomer.Name);

    Console.ReadKey();

    }

    }

    class Customer

    {

    //Declaration of Variable

    private int _id = 0;

    //Property for ID restricted from assigning new values

    public int ID

    {

  • get { return _id; }

    }

    //Declare Variable for name & use Property for Read & Write

    private string _name = string.Empty;

    public string Name

    {

    get { return _name; }

    set { _name = value; }

    }

    //Constructor for passing the initial value(as parameter) to the variables

    public Customer(int id, string name)

    {

    //variable = parameter

    _id = id;

    _name = name;

    }

    //Constructor with 0 arguments

    public Customer()

    {

    //

    }

    }

    Output:

    0 :: Joe

    100 :: Jack

  • Related Videos

    https://www.youtube.com/watch?v=c29e4Zj7gtI

    8.4. C# Code and Naming Conventions

    1. Class Naming Convention - Class names should be nouns, in Pascal casing.

    For e.g; class Customer, class CustomerManager.

    2. Variable Naming Convention - Variable names can be short, but need to be meaningful for

    the purpose. All variable names can start with a lower case first letter and the next word in the

    same start with capital letter. Variable name should be mnemonic that is, designed to indicate

    to the casual observer the intent of its use. One-character variable names should be avoided.

    3. Property Naming Convention Property names are given Similar as that of corresponding

    member, in pascal casing.

    For e.g; Id, Name, BasicPay, RegistrationStatus.

    4. Comments In C#, single line Comments are given using // & multi-Line comments are given

    using /* and */.

    8.5. Practice Problems

    Write a class with a main method that will print you the Name, Designation, and Place on the

    console.

    output should be

    Name: Jacquil

    Designation: Consultant

    Place: LA

    9O9 is a web shoppe which helps the user to purchase their item in a convenient manner. But to

    order the items the user need to register first and then generate an online Bill after the internet

    banking.

  • In this scenario, you might have identified some objects, what are they? What is the name of the

    Class chosen for the Registration details of the User?

    The objects that we can find here are User, Item, Bill. We need an object for the user for the

    registration details.

    To create an object for the user, we need a class with name User. We need variables for taking

    the user details like First Name, Last Name, age and Location and Email ID. We will be passing

    the values to the user object during the time of object creation, so we need a Constructor. Then

    we need to provide Properties for the variables.

    To start with the execution and work with the User class, we will include a Program class with

    Main method.

    Test the User registration by using 3 user objects. Print the name of the user using the objects

    created.

    Output Should be:

    Give the details of users like Haris Jack . Print the Last name, First name of the user as output.

    I.e;

    Jack, Haris

    Solutions:

    class User

    {

    //Variables

    private string _firstname = string.Empty;

    private string _lastname = string.Empty;

    private int _age =0;

    private string _location = string.Empty;

    private string _email = string.Empty;

    //Constructors

  • public User()

    {

    //

    }

    public User(string firstname, string lastname, int age,string location, string

    email)

    {

    _firstname = firstname;

    _lastname = lastname;

    _age = age;

    _location = location;

    _email = email;

    }

    //Properties

    public string FirstName

    {

    get

    {

    return _firstname;

    }

    set

    {

    _firstname = value;

    }

  • }

    public string LastName

    {

    get

    {

    return _lastname;

    }

    set

    {

    _lastname = value;

    }

    }

    public int Age

    {

    get

    {

    return _age;

    }

    set

    {

    _age = value;

    }

    }

    public string Location

  • {

    get

    {

    return _location;

    }

    set

    {

    _location = value;

    }

    }

    public string EmailId

    {

    get

    {

    return _email;

    }

    set

    {

    _email = value;

    }

    }

    }

    class Program

    {

  • static void Main(string[] args)

    {

    //Assign values using constructors.

    User user1 = new User("Haris","Jack", 40, "LA", "[email protected]");

    Console.Write(user1.LastName);

    Console.Write(", ");

    Console.WriteLine(user1.FirstName);

    User user2 = new User();

    //Assign values using properties.

    user2.FirstName = "Robert";

    user2.LastName = "George";

    user2.Age = 60;

    user2.Location = "LA";

    user2.EmailId = "[email protected]";

    Console.Write(user2.LastName);

    Console.Write(", ");

    Console.WriteLine(user2.FirstName);

    //Assign values using constructors by getting input from user.

    Console.WriteLine("Enter first name,last name,age,location and email");

    string firstname = Console.ReadLine();

    string lastname = Console.ReadLine();

    int age = Convert.ToInt32(Console.ReadLine());

    string location = Console.ReadLine();

    string email = Console.ReadLine();

  • User user3 = new User(firstname,lastname,age,location,email);

    Console.Write(user1.LastName);

    Console.Write(", ");

    Console.WriteLine(user1.FirstName);

    Console.ReadKey();

    }

    }

    Output:

    Jack, Haris

    George, Robert

    Enter first name,last name,age,location and email

    Joe

    Wilson

    50

    London

    [email protected]

    Wilson,Joe

    This solution shows 3 types of object creation and data initialization.

  • 9. C# - Access specifiers, Properties and Methods

    Objective

    Overview and Types of Access Specifiers

    Properties Overview and concepts

    Methods Overview and concepts

    9.1. Overview and Types of Access Specifiers

    Access modifiers (or Access Specifiers) are keywords used to specify the declared accessibility

    of a member or a type. There are four access modifiers:

    a. public

    b. protected

    c. internal

    d. private

    The following five accessibility levels can be specified using the access modifiers:

    Public:

    Access is not restricted.

    Protected:

    Access is limited to the containing class or types derived from the containing class.

    Internal:

    Access is limited to the current assembly.

    Protected Internal:

    Access is limited to the current assembly or types derived from the containing class.

  • Private:

    Access is limited to the containing type.

    Types or Classes can only have internal or public accessibility. The default accessibility for these

    types is internal.

    Nested types/classes, which are members of other types/classes, can have declared

    accessibilities as indicated in the following table.

    The following examples demonstrate how to specify access modifiers on a type and member:

    public class Bicycle

    {

    public void Pedal() {

    // pedal implementation

    }

    }

    To set the access level for a class or struct member, add the appropriate keyword to the member

    declaration, as shown in the following example.

    // public class:

    public class Tricycle

    {

  • // protected method:can be accessed in the derived classes

    protected void Pedal() { }

    // private field: can be accessed within the same class

    private int wheels = 3;

    // protected internal property: can be accessed from any class within

    assembly

    protected internal int Wheels

    {

    get { return wheels; }

    }

    }

    9.2. Properties Overview

    A property is a member that provides a flexible mechanism to read, write, or compute the value

    of a private field. Properties can be used as if they are public data members, but they are actually

    special methods called accessors. This enables data to be accessed easily and still helps

    promote the safety and flexibility of methods.

    A property generally has a private data member accompanied by accessor functions and is

    accessed syntactically as a field of a class. (Although properties can have different access levels,

    the more common case is public access.)

    A property definition generally consists of the following two pieces:

    i. Definition of a private data member.

    private int number = 0;

    ii. Definition of a public property using the property declaration syntax. This syntax associates the

    private data member with a public property through get and set accessor functions.

    public int MyNumber

    {

    // Retrieves the number data member.

    get

  • {

    return number;

    }

    // Assigns to the number data member.

    set

    {

    number = value;

    }

    }

    In this second example, the Time class stores a time period. Internally the class stores the time

    in seconds, but a property named Hours enables a client to specify a time in hours. The

    accessors for the Hours property perform the conversion between hours.

    class Time

    {

    private double seconds;

    public double Hours

    {

    get { return seconds / 3600; }

    set { seconds = value * 3600; }

    }

    }

    class Program

    {

    static void Main()

    {

    Time t = new Time();

    // Assigning the Hours property causes the 'set' accessor to be called.

    t.Hours = 24;

    // Evaluating the Hours property causes the 'get' accessor to be called.

    Console.WriteLine("Time in hours: " + t.Hours);

  • }

    }

    // Output: Time in hours: 24

    The term value is a keyword in the syntax for the property definition. The variable value is

    assigned to the property in the calling code.

    The type of a property can be a primitive type, a collection of primitive types, a user-defined type,

    or a collection of user-defined types.

    Properties enable a class to expose a public way of getting and setting values, while hiding

    implementation or verification code.

    A get property accessor is used to return the property value, and a set accessor is used to assign

    a new value. These accessors can have different access levels.

    The value keyword is used to define the value being assigned by the set accessor.

    Properties that do not implement a set accessor are read only.

    Video on C# More on Classes

    http://channel9.msdn.com/Series/C-Sharp-Fundamentals-Development-for-Absolute-

    Beginners/Understanding-and-Creating-Classes-14

    9.3. Methods Overview

    A method is a code block that contains a series of statements. A program causes the statements

    to be executed by calling the method and specifying any required method arguments. In C#,

    every executed instruction is performed in the context of a method. The Main method is the entry

    point for every C# application and when the program is started it is called by the CLR.

    Basic characteristics of methods are:

    1. Access level

    2. Return value type

    3. Method name

    4. Method parameters

    5. Parentheses

    6. Block of statements

    Access Level

  • Access level of methods is controlled with access modifiers. They set the visibility of methods.

    They determine who can call the method. In the following class method GetTopSpeed can be

    accessed by any class since it is public. In this Example it is called within the Main method in the

    same class.

    class TestMotorcycle

    {

    public double GetTopSpeed()

    {

    return 108.4;

    }

    static void Main()

    {

    TestMotorcycle moto = new TestMotorcycle();

    double speed = moto.GetTopSpeed();

    Console.WriteLine("My top speed is {0}", speed);

    }

    }

    Return Value

    Methods may return a value to the caller. In case our method returns a value, we provide its data

    type. If not, we use the void keyword to indicate that our method does not return values. Method

    parameters are surrounded by parentheses and separated by commas. Empty parentheses

    indicate that the method requires no parameters. The method block is surrounded with { }

    characters. The block contains one or more statements that are executed, when the method is

    invoked. In the following example, the method calculateArea() returns the variable Area as a

    double value.

    class ReturnTest

    {

    static double CalculateArea(int r)

    {

  • double area = r * r * Math.PI;

    return area;

    }

    static void Main()

    {

    int radius = 5;

    double result = CalculateArea(radius);

    Console.WriteLine("The area is {0:0.00}", result);

    // Keep the console open in debug mode.

    Console.WriteLine("Press any key to exit.");

    Console.ReadKey();

    }

    }

    // Output: The area is 78.54

    Method Signature

    A method signature is a unique identification of a method for the C# compiler. The signature

    consists of a method name and the type and kind (value, reference, or output) of each of its

    formal parameters. Method signature does not include the return type.

    The following example shows a set of overloaded method declarations along with their

    signatures.

    void F(); // F()

    void F(int x); // F(int)

    void F(ref int x); // F(ref int)

    void F(int x, int y); // F(int, int)

    Note that any ref and out parameter modifiers are part of the method signature. F(int) and F(ref

    int) are unique signatures.

    Method Access

  • Calling a method on an object is like accessing a field. After the object name, add a period, the

    name of the method, and parentheses. Arguments are listed within the parentheses, and are

    separated by commas (if there are multiple arguments).

    Static methods can be called using Class name then add a period, the name of the method and

    parenthesis with arguments.

    In the following example, method CalculateArea is called in the Console's Main method in the

    Program class. The method is accessed as test.CalculateArea(radius) where test is the object of

    the ReturnTest class.

    class ReturnTest

    {

    public double CalculateArea(int r)

    {

    double area = r * r * Math.PI;

    return area;

    }

    }

    class Program

    {

    static void Main()

    {

    ReturnTest test = new ReturnTest();

    double result = test.CalculateArea(10);

    Console.WriteLine("The area is {0:0.00}", result);

    // Keep the console open in debug mode.

    Console.WriteLine("Press any key to

    exit.");

    Console.ReadKey();

    }

    }

  • In the following example, static method CalculateArea is called in the Console's Main method in

    the Program class. The method is accessed as Returntest. CalculateArea(radius) where

    ReturnTest class is used directly to access the method.

    class ReturnTest

    {

    public static double CalculateArea(int r)

    {

    double area = r * r * Math.PI;

    return area;

    }

    }

    class Program

    {

    static void Main()

    {

    //Method is called using the Class name and dot operator

    double result = ReturnTest.CalculateArea(10);

    Console.WriteLine("The area is {0:0.00}", result);

    // Keep the console open in debug mode.

    Console.WriteLine("Press any key to

    exit.");

    Console.ReadKey();

    }

    }

    Method Parameters

    The method definition specifies the names and types of any parameters that are required. When

    a program calls the method, it provides concrete values called arguments for each parameter.

    The arguments must be compatible with the parameter type.

    In the following example, method CalculateBMI is called passing the arguments 123(weight) and

    64(height).

  • class ParameterExample

    {

    static void Main(string[] args)

    {

    // The method can be called by passing arguments for the

    parameters

    int bmi = CalculateBMI(123, 64);

    Console.WriteLine( bmi);

    }

    static int CalculateBMI(int weight, int height)

    {

    return (weight * 703) / (height * height);

    }

    }

    Pass By Ref and Pass By Value

    By default, when a value type is passed in a method, a copy is passed instead of the object itself.

    Therefore, changes to the argument have no effect on the original copy in the calling method.

    When an object of a reference type is passed in a method, a reference to the object is passed.

    That is, the method receives not the object itself but an argument that indicates the memory

    location of the object. If we change a member of the object by using this reference, the change is

    reflected in the argument in the calling method.

    In the following example, Method is called passing argument by ref and the changes done in the

    method reflected in the output(45).

    When the method ValMethod is called where the argument is passed by value, there is no

    change in the value(val) and output is 45.

    class RefExample

    {

    static void Method(ref int i)

    {

  • i = i + 44;

    }

    static void ValMethod(int i)

    {

    i = i + 44;

    }

    static void Main()

    {

    int val = 1;

    Method(ref val);

    Console.WriteLine(val);

    // Output: 45

    ValMethod(val);

    Console.WriteLine(val);

    // Output: 45

    }

    }

    Return Values

    Methods can return a value to the caller. If the return type, the type listed before the method

    name, is not void, the method can return the value by using the return keyword. A statement with

    the return keyword followed by a value that matches the return type will return that value to the

    method caller. The return keyword also stops the execution of the method. If the return type is

    void, a return statement without a value is still useful to stop the execution of the method. Without

    the return keyword, the method will stop executing when it reaches the end of the code block.

    Methods with a non-void return type are required to use the return keyword to return a value.

    In the following example method CalculateTax returns calculated Tax to the calling method. The

    returned value is assigned to the taxAmount variable.

    Method PrintTax does not have a return value. So when this method is called it prints the Tax

    value to the Console and it exits when the end of the code block is reached.

  • class ReturnExample

    {

    static void Main(string[] args)

    {

    // The method can be called by passing arguments for the parameters

    Tax oTax = new Tax();

    double taxAmount = oTax.CalculateTax(1000000, 20);

    oTax.PrintTax(taxAmount);

    Console.ReadLine();

    }

    }

    class Tax

    {

    public double CalculateTax(double Amount, double taxRate)

    {

    return (Amount * taxRate) / 100;

    }

    public void PrintTax(double TaxAmount)

    {

    //print the tax amount to the console

    Console.WriteLine(TaxAmount.ToString());

    }

    }

    Video on C# More on Classes

    http://channel9.msdn.com/Series/C-Sharp-Fundamentals-Development-for-Absolute-

    Beginners/More-about-Classes-and-Methods-15

  • 10. C# - Working with Collections

    Objective

    To store and process with a set of objects.

    Learn generic and non-generic collection and its usage.

    10.1. Array

    Array is used to store multiple values of same type in a variable.

    It is used to store values of value types and reference types

    Size of the array should be decided at the time of creation itself.

    Syntax:

    dataType[] varName=new dataType[size];

    Eg int[] marks=new int[10];

    marks is an integer array which can hold 10 integer values.

    Array store from index 0 till size-1 values. 'marks' array can hold values from marks[0] to

    marks[9].

    Sample which stores and retrieve the marks of 5 subjects

    static void Main(string[] args)

    {

    int[] marks = new int[5];

    Console.WriteLine("Enter marks of 5 subjects");

  • for (int i = 0; i < 5; i++)

    {

    marks[i] = Convert.ToInt32(Console.ReadLine());

    }

    Console.WriteLine("Marks are as follows: ");

    for (int i = 0; i < 5; i++)

    {

    Console.WriteLine(marks[i]);

    }

    Console.ReadKey();

    }

    Output:

    Enter marks of 5 subjects

    78

    89

    67

    98

    72

    Marks are as follows:

    78

    89

    67

    98

    72

    In case we have to store set of employee details then we can use array of type class. So in the

    following sample, for each employee we have to store name, id and performance pay. So first we

    create an employee array with the required attributes and a constructor is written to assign the

    values and there are properties used to retrieve the values.

    In our main program the employee array is created and values are stored and finally retrieved.

    The size of employee array is 100. So it can store a maximum of 100 employees.

  • //In the following line and Array of type employee is created

    Employee[] empList = new Employee[100];

    //In the following line the object of type employee is created by passing the required values and

    storing it in array.

    empList[i] = new Employee(name, id, performancePay);

    //In the following line the Id of employee is accessed from array.

    Console.WriteLine("Id is "+empList[i].Id);

    Sample:

    class Employee

    {

    string name;

    int id;

    int performancePay;

    public Employee(string name, int id, int performancePay)

    {

    this.name = name;

    this.id = id;

    this.performancePay = performancePay;

    }

    public string Name

    {

    get

    {

    return (name);

    }

    set

    {

    name = value.ToUpper();

    }

    }

  • public int PerformancePay

    {

    get

    {

    return (performancePay);

    }

    set

    {

    performancePay = value;

    }

    }

    public int Id

    {

    get

    {

    return (id);

    }

    set

    {

    id = value;

    }

    }

    class Program

    {

    static void Main(string[] args)

    {

    //Array of type employee is created

    Employee[] empList = new Employee[100];

    string name;

    int id;

    int performancePay;

    for (int i = 0; i < 100; i++)

  • {

    Console.WriteLine("Enter name,id,performance pay");

    name=Console.ReadLine();

    id=Convert.ToInt32(Console.ReadLine());

    performancePay=Convert.ToInt32(Console.ReadLine());

    //ith employee object is created

    empList[i] = new Employee(name, id, performancePay);

    }

    //View the details of all the employees

    for (int i = 0; i < 100; i++)

    {

    Console.WriteLine("Details of Employee no :"+ i+1);

    Console.WriteLine("Id is "+empList[i].Id);

    Console.WriteLine("Name is "+empList[i].Name);

    Console.WriteLine("Performance Pay is

    "+empList[i].PerformancePay);

    }

    Console.ReadKey();

    }

    }

    10.2. Array list

    Array list provides a dynamically sized array of objects

    There is no size limit for array list

    It is a non-generic collection. We can store values of any type

    Appending elements is efficient compared to Array, but inserting elements can be slow.

    We can perform add, edit, delete and display in array list.

    In the top of the page along with other using statements add

    using System.Collections; to access array list class.

    Syntax for array list declaration

  • ArrayList list = new ArrayList();

    Syntax to add elements:

    listName.Add(object);

    object can be of any type.

    Syntax to remove an element from list:

    listName.Remove(object);

    It is simple for Array list to store 3 values, display them and remove a value

    static void Main(string[] args)

    {

    ArrayList list = new ArrayList();

    //Adds value to the list

    list.Add(10);

    list.Add(20);

    list.Add(30);

    //Display all the values in a list

    foreach (int i in list)

    {

    Console.WriteLine(i);

    }

    //Remove the values from the list

    list.Remove(20);

    //Display all the values in a list

    foreach (int i in list)

    {

  • Console.WriteLine(i);

    }

    Console.ReadKey();

    }

    Output

    10 ----All the values in the list

    20

    30

    10---The result after removing 20 from the list

    30

    A company has a set of departments. We will see how to add department to the arraylist, how to

    change the existing details, how to delete a department and finally view the department's details

    class Department

    {

    string name;

    int id;

    public Department(string name, int id)

    {

    this.name = name;

    this.id = id;

    }

    public string Name

    {

    get

  • {

    return (name);

    }

    set

    {

    name = value;

    }

    }

    public int Id

    {

    get

    {

    return (id);

    }

    set

    {

    id = value;

    }

    }

    }

    class Program

    {

    static void Main(string[] args)

    {

  • ArrayList list = new ArrayList();

    int choice;

    string name;

    int id;

    do

    {

    Console.WriteLine("Menu");

    Console.WriteLine("1.Add new department");

    Console.WriteLine("2.Change department name");

    Console.WriteLine("3.Delete a department");

    Console.WriteLine("4.View all departments");

    Console.WriteLine("5.Exit");

    Console.WriteLine("Enter your choice");

    choice = Convert.ToInt32(Console.ReadLine());

    switch (choice)

    {

    case 1:

    Console.WriteLine("Enter id,name");

    id = Convert.ToInt32(Console.ReadLine());

    name = Console.ReadLine();

    //Create a department object

    Department d = new Department(name, id);

    //Add the department object to the list

    list.Add(d);

  • break;

    case 2:

    Console.WriteLine("Enter id of the department");

    id = Convert.ToInt32(Console.ReadLine());

    Console.WriteLine("Enter the new name of the department");

    name = Console.ReadLine();

    //Loop through the department array list to find if the department

    exists & change the name

    //if the department with the specified

    id exists

    foreach (Department dept in list)

    {

    //checks the department id

    if (dept.Id == id)

    {

    //change the name of the department

    dept.Name = name;

    }

    }

    break;

    case 3:

    Console.WriteLine("Enter id of the department");

    id = Convert.ToInt32(Console.ReadLine());

    //Loop through the department array list to find

  • if the department with that id exists

    //and delete the department

    foreach (Department dept in list)

    {

    //checks the department id

    if (dept.Id == id)

    {

    //removes the department from the list

    list.Remove(dept);

    //break statement is mandatory since an item is removed from the

    list

    //the iteration can not continue further

    break;

    }

    }

    break;

    case 4:

    //Loop through the department list and view all the department

    details

    foreach (Department dept in list)

    {

    Console.WriteLine("Id is " + dept.Id);

    Console.WriteLine("Name is " + dept.Name);

    }

  • break;

    }

    } while (choice != 5);

    Console.ReadKey();

    }

    }

    Output

    Menu

    1.Add new department

    2.Change department name

    3.Delete a department

    4.View all departments

    5.Exit

    Enter your choice

    1

    Enter id,name

    1

    Admin

    Menu

    1.Add new department

    2.Change department name

    3.Delete a department

    4.View all departments

    5.Exit

  • Enter your choice

    1

    Enter id,name

    2

    HR

    Menu

    1.Add new department

    2.Change department name

    3.Delete a department

    4.View all departments

    5.Exit

    Enter your choice

    4

    Id is 1

    Name is Admin

    Id is 2

    Name is HR

    Menu

    1.Add new department

    2.Change department name

    3.Delete a department

    4.View all departments

    5.Exit

    Enter your choice

  • 2

    Enter id of the department

    2

    Enter the new name of the department

    IS

    Menu

    1.Add new department

    2.Change department name

    3.Delete a department

    4.View all departments

    5.Exit

    Enter your choice

    4

    Id is 1

    Name is Admin

    Id is 2

    Name is IS

    Menu

    1.Add new department

    2.Change department name

    3.Delete a department

    4.View all departments

    5.Exit

    Enter your choice

  • 3

    Enter id of the department

    1

    Menu

    1.Add new department

    2.Change department name

    3.Delete a department

    4.View all departments

    5.Exit

    Enter your choice

    4

    Id is 2

    Name is IS

    Menu

    1.Add new department

    2.Change department name

    3.Delete a department

    4.View all departments

    5.Exit

    Enter your choice

    5

  • 10.3. Generic list

    List provides a dynamically sized set of objects of same type.

    Generic collections are type safe since it allows only the specified types of input to be

    added to the list

    It is a generic collection.

    We can perform add, edit, delete and display in generic list.

    We have to add the namespace using System.Collections.Generic; to access generic list

    Syntax:

    List list = new List();

    --dataType can be primitive data-Types or classes

    eg.

    List intList = new List();

    Creates an integer list which can store any number elements

    List namelist = new List();

    Creates an name list which stores a set of names

    List list = new List();

    This list can process with a set of departments.

    Syntax to add elements:

    listName.Add(object);

    Syntax to remove an element from list:

    listName.Remove(object);

    Sample program which will process a set of projects shown below. Using this sample add,

    update, delete and display operations are performed

    class Project

    {

    string name;

  • int id;

    public Project(string name, int id)

    {

    this.name = name;

    this.id = id;

    }

    public string Name

    {

    get

    {

    return (name);

    }

    set

    {

    name = value;

    }

    }

    public int Id

    {

    get

    {