Friday, 4 March 2011

Chapter 1 Basic C# Introduction

Basics of C#


C# is a very powerful language yet it has only 90 or so keywords. According to Microsoft it is easy to learn specially for people with background in C, C++, and Java. It has all the bells and whistles that you expect from a modern language.As this is an object oriented language therefore it supports encapsulation,polymorphism and inheritance.People who are familiar with C and C++ will find their old friend struct in C#. As we all know C# is a completely new language thus it is free from backward compatibility curse and cuts quite a bit of flab from other languages.
The C# build process is simple compared to C and C++ and more flexible than in Java. There are no separate header files, and no requirement that methods and types be declared in a particular order. A C# source file may define any number of classes, structs, interfaces, and events.

Thursday, 3 March 2011

Chapter 2 Introduction to Visual Studio IDE(for C#)

The development environment provided by Microsoft for C# is one of the best IDE if not the best. This product is a trend setter and all other IDE's try to copy its features. It is so rich in feature that it is hard to enumerate each and every little tricks it has. To understand this environment you have to do it yourself. Best part of the IDE is user can change it and customize it according to his/her needs.
Some of the most important Tools you might require for C# are all available under the view menu.
  • The Code Editor, for writing source code.
  • The C# compiler, for converting C# source code into an executable program.
  • The Visual Studio debugger, for testing your program.
  • The Toolbox and Designer, for rapid development of user interfaces using the mouse.
  • Solution Explorer, for viewing and managing project files and settings.
  • Project Designer, for configuring compiler options, deployment paths, resources, and more.
  • Class View, for navigating through source code according to types, not files.
  • Properties Window, for configuring properties and events on controls in your user interface.
  • Object Browser, for viewing the methods and classes available in dynamic link libraries including .NET Framework assemblies and COM objects.
  • Document Explorer, for browsing and searching product documentation on your local machine and on the Internet.

Editor and Windows Form Designer Windows


The large main window is used by both the Code Editor and the Windows Forms Designer. You can toggle between code view and Design view by pressing F7, or clicking Code or Designer on the View menu. While in Design view, you can drag controls onto the window from the Toolbox, which you can make visible by clicking on the Toolbox tab on the left margin.

The Visual C# Code Editor is a word processor for writing source code. Just as Microsoft Word provides extensive support for sentences, paragraphs, and grammar, the C# Code Editor does the same for C# syntax and the .NET Framework. This support can be grouped into five main categories:
  • IntelliSense:Continually updated basic documentation on .NET Framework classes and methods as you type them in the editor, as well as automatic code generation.
  • Refactoring:Intelligent restructuring of your code base as it evolves over the course of a development project.
  • Code snippets: A library you can browse that contains frequently repeated code patterns.
  • Wavy underlines: Visual notifications of misspelled words, erroneous syntax, and warning situations as you type.
  • Readability aids: Outlining and colorization.

IntelliSense

IntelliSense is the name of a set of related features that are designed to minimize the time you spend looking for help and to help you enter code more accurately and efficiently. These features all provide basic information about language keywords, .NET Framework types, and method signatures as you type them in the editor. The information is displayed in ToolTips, list boxes, and smart tags.

Completion Lists

As you enter source code in the editor, IntelliSense displays a list box that contains all the C# keywords and .NET Framework classes. If it finds a match in the list box for the name that you are typing, it selects the item. If the selected item is what you want, you can simply hit TAB and Intellisense will finish entering the name or keyword for you. For more information, see Completion Lists in C#.

Quick Info

When you hover the cursor over a .NET Framework type, IntelliSense will display a Quick Info ToolTip that contains basic documentation about that type.

List Members


When you enter a .NET Framework type into the Code Editor, and then type the dot operator (.), IntelliSense displays a list box that contains the members of that type. When you make a selection and press TAB, IntelliSense enters the member name.

Parameter Info

When you enter a method name in the Code Editor, and then type an opening parentheses, IntelliSense will display a Parameter Info ToolTip that shows the order and types of the method's parameters. If the method is overloaded, you can scroll down through all the overloaded signatures.


Add usings


Sometimes you may attempt to create an instance of a .NET Framework class without a sufficiently qualified name. When this happens, IntelliSense displays a smart tag after the unresolved identifier. When you click the smart tag, IntelliSense displays a list of using directives that will enable the identifier to be resolved. When you select one from the list, IntelliSense adds the directive to the top of your source code file and you can continue coding at your current location.

Refactoring

As a code base grows and evolves over the course of a development project, it is sometimes desirable to make changes in order to make it more readable to humans, or more portable. For example, you may want to split some methods up into smaller methods, or change method parameters, or rename identifiers. The Refactoring feature, which is accessible by right-clicking in the Code Editor, does all this in a way that is much more convenient, intelligent, and thorough than traditional tools such as search and replace.

Code Snippets

Code snippets are small units of commonly used C# source code that you can enter accurately and quickly with only a couple of keystrokes. The code snippet menu is accessed by right-clicking in the Code Editor. You can browse from among the many snippets provided with Visual C#, and you can also create your own.

Wavy underlines

Wavy underlines give you instant feedback on errors in your code as you type. A red wavy underline identifies a syntax error such as a missing semicolon or mismatched braces. A green wavy underline identifies a potential compiler warning, and blue identifies an Edit and Continue issue. The following illustration shows a red wavy underline:



Readability Aids

Outlining

The Code Editor automatically treats namespaces, classes, and methods as regions that you can collapse in order to make other parts of the source code file easier to find and read. You can also create your own collapsible regions by surrounding code with the #region and #endregion directives.



Colorization

The editor gives different colors to the various categories of identifiers in a C# source code file.


The Properties window in the lower right is populated only in Design view. It enables you to set properties and hook up events for user interface controls such as buttons, text boxes, and so on. When you set this window to Auto Hide, it will collapse into the right margin whenever you switch to Code View.

Solution Explorer and Project Designer

The window in the top right is Solution Explorer, which shows all the files in your project in a hierarchical tree view. When you use the Project menu to add new files to your project, you will see them reflected in Solution Explorer. In addition to files, Solution Explorer also displays your project settings, and references to external libraries required by your application.

The Project Designer property pages are accessed by right-clicking on the Properties node in Solution Explorer, and then clicking Open. Use these pages to modify build options, security requirements, deployment details, and many other project properties.

Compiler, Debugger, and Error List Windows


The C# compiler has no window because it is not an interactive tool, but you can set compiler options in the Project Designer. When you click Build on the Build menu, the C# compiler is invoked by the IDE. If the build is successful, the status pane displays a Build Succeeded message. If there were build errors, the Error List window appears below the editor/designer window with a list of errors. Double-click an error to go to the problem line in your source code. Press F1 to see Help documentation for the highlighted error.

The debugger has various windows that display values of variables and type information as your application is running. You can use the Code Editor window while debugging to specify a line at which to pause execution in the debugger, and to step through code one line at a time.

Customizing the IDE

All of the windows in Visual C# can be made dockable or floating, hidden or visible, or can be moved to new locations. To change the behavior of a window, click the down arrow or push-pin icons on the title bar and select from among the available options. To move a docked window to a new docked location, drag the title bar until the window dropper icons appear. While holding down the left mouse button, move the mouse pointer over the icon at the new location. Position the pointer over the left, right, top or bottom icons to dock the window on the specified side. Position the pointer over the middle icon to make the window a tabbed window. As you position the pointer, a blue semi-transparent rectangle appears, which indicates where the window will be docked in the new location.

Wednesday, 2 March 2011

Chapter 3 Your First C# Program

Now lets start writing our first C# program. You will see that C# can create many different kind of programs. Each program is called a project. It is very important to understand the concept of projects. A project is a collection of programs and resources under one name and treated as a single unit. Thus if we are creating a software, it is not necessary to have different files strewn everywhere, instead each file and code is categorized and kept under one roof called project and when needed they are compiled.
C# has many different kind of projects, each project has its own distinct features, like some are for Form based programming, some are for console only, some for the web etc. In this chapter for illustration purpose we will take the simplest of all the Console Application. So without further delay fire up your Visual Studio IDE

STEP1

Open Visual Studio and click on File menu

STEP 2

Choose the New Project option from the File menu, it will show New Project Dialog Box as shown in the figure given below. Depending on your configuration you may have more or less amount of items in this window. Please click on the Visual C# entry to the left of the Dialog Box, it will bring up all the project types under C#. From that list choose Console Application. At the bottom of this dialog you will find Application Name entry, please change it to something appropriate in our case I will name it HelloWorld


STEP 3

You will be resented with this window, this is the IDE giving you a skeletal C# program pre-written for you. It does not do anything for now but saves lot of your time typing mundane and repetitive lines. We will modify the code and add a single line.



using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace HelloWorld
{
  class Program
  {
    static void Main(string[] args)
    {
      Console.WriteLine("Hello World, Welcome to C#");
    }
  }
}
Check the extra line added Console.WriteLine, this is the statement which will print a message given inside the quotes on the screen when we will execute this code.

STEP 4

To execute this program we must compile it first and check for any errors. As this program is just a basic C# code lets do it in one go and compile and execute it together.
If we press F5 it will start the BUILD(Compile) and execute the code inside the debugger(it will be explained later) Unfortunately our program is so short that you will only see the console window flashing and the closing.
Thus we will use Ctrl + F5 which starts without the debugger and after completion keeps the window open until you press some key. The output of your program should be something like the figure given below




Congratulation you have written your first C# program. Please feel free to read online documentation and modify the program as you wish, I will expand on this program and its various parts in the next post.


Chapter 4 Hello World C# Program

using System;

namespace HelloWorld
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World, Welcome to C#");
        }
    }
}

using

using System;
This is another keyword which tells the compiler that we are going to use all the classes in the namespace system. Thus we have used Console.WriteLine. Point to be noted is we cannot use classes which are inside internal namespace like System.Text.

namespace

Let us first look at namespace. This is a group of related classes put under one name to keep them distinct. Lets say two different programmers decide to name their classes as SocketListen and even Foundation classes also have the same class called SocketListen, unfortunately this will cause a conflict and it is impossible to stop such incidences, plus we cannot ask anybody to change the class name because other parts might be dependent on that class. To avoid that every class is kept under a unique namespace, therefore even if we have multiple classes with the same name yet they are categorized by their namespace. So my class will be referred as helloworld.program and if their is another program in the foundation classes with the same name it might be referred as system.program.
Thos of you that have migrated from JAVA namespaces in C# is a bit different in the way they are organised on the disk. In C# namespace classes can be stored in different folders. Namespace may contain classes, delegates events and internal namespaces too.

class

A C# program can have more than one classes. Each class can contain functions,data,events etc. A more detailed explanation of class will be take n up when we discuss OOPS.

Main

Students from Java, C++, C background will recognize this function as the starting point of your program. In a technical term it is called entry point for the program. As you might have noticed there is a static keyword, this is because Main function is called by CLR without declaring an object of our class 'program'. The string[] args is called command line parameters. These are given when you execute your program from the DOS shell and want to pass some value like copy a.txt b.txt The text in Bold is called the command line parameter.
Few important points to remember are that all complete C# statement end by a (;).
Each block of code is demarcated by opening and closing curly brackets {}
Indentation while not compulsory is desirable and makes the reading more user friendly but it has no effect on compilation.
Comments can be given by using (//). You can give as many comments as you want because these are not compiled by C# compiler.

Let us make little modification to the original code
using System;

namespace HelloWorld
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Enter your name student : ");
            string name = Console.ReadLine();
            Console.WriteLine("Hello student {0}, Welcome to the amazing world of C#",name);
        }
    }
}

In the above program we have asked for an input from the user through the statement Console.ReadLine and stored the value entered in a string type variable, then used the Console.WriteLine function to print it. Please note that the {0} is the placeholder for the argument name given at the end of the WriteLine statement.
If you have written it correctly then the Console window will ask for your name and then print the message as shown in the next figure


In the next chapter we will discuss the basic data types,variables,constant etc

Monday, 28 February 2011

Chapter 5 An Introduction to C# Data-Types

 
As we all know every programming language has Constants and Variables. These can be of different types. Basically there are two kinds of constants Numeric and Alpha-Numeric or String. Thus to store these values we need different type of variables. Obviously same two classification applies but under numeric they can be signed,unsigned,float,double etc. We call these classifications based on the values stored as data types. This chapter will look into the different data types in C#.

In C# Data Types are broadly categorized in two parts
  1. Value Types which store values, or
  2. Reference Types, which store references to the actual data.
We will discuss the second type at a later stage. Lets look at first type in detail in this chapter.

Value Types
These can be further divided in
  • Structs
  • Enumerations
Structs

Now we will see the most basic kind of datatypes under the Struct type
  1. Numeric types
    1. Integral types
    2. Floating-point types
    3. decimal
  2. bool
  3. User defined structs.
Features Of Value Types
  1. These variables work with values only therefore one when one variable is assigned to another the value is copied unlike the reference type where the reference is copied
  2. All value types are derived implicitly from the System.ValueType.Go to .NET framework type table
  3. We cannot create a new type by using a value type.
  4. Each type has a implicit constructor which initializes the variable with a default value.Go to default value table
  5. All the value types are aliases of .NET Framework System types. e.g int is the alias for System.Int32
  6. Unlike reference types, it is not possible for a value type to contain the null value.
Local variables in C# must be initialized before being used. Therefore, if you declare a local variable without initialization like this:

int myInt;
you cannot use it before you initialize it. You can initialize it using the following statement:

myInt = new int();  // Invoke default constructor for int type.
which is equivalent to:

myInt = 0;         // Assign an initial value, 0 in this example.
You can, of course, have the declaration and the initialization in the same statement like this:

int myInt = new int();

–or–

int myInt = 0;

Using the new operator calls the default constructor of the specific type and assigns the default value to the variable. In the preceding example, the default constructor assigned the value 0 to myInt.

With user-defined types, use new to invoke the default constructor. For example, the following statement invokes the default constructor of the Point struct:

Point p = new Point(); // Invoke default constructor for the struct.

After this call, the struct is considered to be definitely assigned; that is, all of its members are initialized to their default values.

Integral Types

The following table shows the sizes and ranges of the integral types, which constitute a subset of simple types.
Type Range Size
int -2,147,483,648 to 2,147,483,647 Signed 32-bit integer
uint 0 to 4,294,967,295 Unsigned 32-bit integer
long -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 Signed 64-bit integer
ulong 0 to 18,446,744,073,709,551,615 Unsigned 64-bit integer
ushort
0 to 65,535

Unsigned 16-bit integer
short -32,768 to 32,767 Signed 16-bit integer
char U+0000 to U+ffff Unicode 16-bit character
byte
0 to 255
Unsigned 8-bit integer
sbyte -128 to 127 Signed 8-bit integer
If the value represented by an integer literal exceeds the range of ulong, a compilation error will occur.

Floating-Point Types


Type Approximate range Precision
float ±1.5e−45 to ±3.4e38 7 digits
double ±5.0e−324 to ±1.7e308 15-16 digits


Decimal Type


The decimal keyword denotes a 128-bit data type. Compared to floating-point types, the decimal type has a greater precision and a smaller range, which makes it suitable for financial and monetary calculations. The approximate range and precision for the decimal type are shown in the following table.
Type Approximate range Precision
decimal ±1.0 × 10−28 to ±7.9 × 1028 28-29 significant digits

If you want a numeric real literal to be treated as decimal, use the suffix m or M, for example:
decimal xMoni = 10.4m;
Without the suffix m, the number is treated as a double, thus generating a compiler error.

Conversions

The integral types are implicitly converted to decimal and the result evaluates to decimal. Therefore you can initialize a decimal variable using an integer literal, without the suffix, as follows:
decimal xPaisa = 200;
There is no implicit conversion between floating-point types and the decimal type; therefore, a cast must be used to convert between these two types. For example:
decimal xPaisa = 199.9m;
double xd = (double)xPaisa;
xPaisa = (decimal)xd;
You can also mix decimal and numeric integral types in the same expression. However, mixing decimal and floating-point types without a cast results in a compilation error.

Default Values


Value type Default value
bool false
byte 0
char '\0'
decimal 0.0M
double 0.0D
enum The value produced by the expression (E)0, where E is the enum identifier.
float 0.0F
int 0
long 0L
sbyte 0
short 0
struct The value produced by setting all value-type fields to their default values and all reference-type fields to null.
uint 0
ulong 0
ushort 0



.NET Framework Types and C# Aliases


The following table shows the keywords for built-in C# types, which are aliases of predefined types in the System  namespace.
C# Type .NET Framework Type
bool System.Boolean
byte System.Byte
sbyte System.SByte
char System.Char
decimal System.Decimal
double System.Double
float System.Single
int System.Int32
uint System.UInt32
long System.Int64
ulong System.UInt64
object System.Object
short System.Int16
ushort System.UInt16
string System.String

Saturday, 26 February 2011

Chapter 6 Operators In C#


Operators in C#

Every programming language must have Arithmetic Operators. Given below are the Arithmetic Operators used in C#
Operand Description

+

Addition

-

Subtract

*

Multiply

/

Divide

%

Modulo

++

Increment By 1

--

Decrement By 1



Assignment Operator

To transfer values from one variable to another or to assign vales to a variable we use these operators,
Operand Description

=

Simple assignment

-=

Subtract assignment

*=

Multiply assignment

/=

Divide assignment

%=

Modulo assignment

+=

Additive assignment

<<=




left-shift assignment operator

>>=

left-shift assignment operator

&=

AND assignment operator

^=

exclusive-OR assignment operator

|=

OR assignment operator

??

The ?? operator returns the left-hand operand if it is not null, or else it returns the right operand




Relational Operator

In a condition when we need to compare two variables or values. These operators are used in such cases
Operand Description

==

Equality

>

Greater than

<

Less than

!=

Not equals

>=

Greater than equal to

<=

Less than equal to


Conditional Operator

These are operators used to combine two or more conditions to produce one single result
There are basically two logical operators &&(and) ||(or) . We will read there usage a bit later
But to clarify my point, let us assume you have one condition A and another condition B, each of these condition can only be true or false, thus the number of permutation becomes 4. So if we use logical operator we can combine them to produce one single output

Usage Of OR

Condition A Condition B A OR B

false

false

false

true

false

true

false

true

true

true

true

true

Usage Of AND

Condition A Condition B A AND B

false

false

false

true

false

false

false

true

false

true

true

true

Lets look at an example to illustrate my point
/**
 * Author         : vblord
 * Date            : 07/03/2011
 * Difficulty      : Very Easy
 * Description  :  If a student is older than 18 years and a citizen of India 
 *                   only then he/she is permitted to open an account in our bank. 
 *                   This program shows the usage of logical operator AND
 */

using System;

namespace HelloWorld
{
    class LogicalOperand
    {
        static void Main(string[] args)
        {
            Console.Write("Enter age of the student : ");
            int age = System.Int32.Parse(Console.ReadLine());
            Console.Write("Are you a citizen of India (Y/N) : ");
            char citizen = char.Parse(Console.ReadLine());
            if (age > 18 && citizen == 'Y'){
                Console.WriteLine("Hello student you are elligible to open a bank account with us");
            }
            else {
                Console.WriteLine("Hello student you are NOT ALLOWED to open a bank account with us");
            }
            
            Console.ReadKey(false);
        }
    }
}


Bitwise/Logical Operator

These are operators work on each bit of the operands if they are not boolean. It is very useful when each bit packs some information and we nned to read each of them
Operand Description

&

Logical AND

|

Logical OR

!

Logical NOT

^

Logical XOR


Lets investigate & a bit more deeply. Here are the few salient points
The unary & operator returns the address of its operand (requires unsafe context).
Binary & operators are predefined for the integral types and bool. For integral types, & computes the logical bitwise AND of its operands. For bool operands, & computes the logical AND of its operands; that is, the result is true if and only if both its operands are true.
The & operator evaluates both operators regardless of the first one's value.
/**
 * Author         : vblord
 * Date            : 07/03/2011
 * Difficulty      : Very Easy
 * Description  :  Shows the usage of Bitwise & with Integer and Boolean values
 */

using System;
class MainClass
{
    static void Main() 
    {
        Console.WriteLine(true & false); // logical and
        Console.WriteLine(true & true);  // logical and
        Console.WriteLine("0x{0:x}", 0xf8 & 0x3f);  // bitwise and
    }
}

Shift Operator

There are two shift operators << (left shift) and >> (right shift) The shift the first operand left or right by the number of bits specified in the second operand.

>>
If the first operand is an int or uint (32-bit quantity), the shift count is given by the low-order five bits of the second operand (second operand & 0x1f).
If the first operand is a long or ulong (64-bit quantity), the shift count is given by the low-order six bits of the second operand (second operand & 0x3f).
If the first operand is an int or long, the right-shift is an arithmetic shift (high-order empty bits are set to the sign bit). If the first operand is of type uint or ulong, the right-shift is a logical shift (high-order bits are zero-filled).

<<
If first operand is an int or uint (32-bit quantity), the shift count is given by the low-order five bits of second operand.
If first operand is a long or ulong (64-bit quantity), the shift count is given by the low-order six bits of second operand.
The high-order bits of first operand are discarded and the low-order empty bits are zero-filled. Shift operations never cause overflows.

Additionally there are few more operators used by C# namely [] which is used for arrays, indexers, and attributes. They can also be used with pointers.

()In addition to being used to specify the order of operations in an expression, parentheses are used to specify casts, or type conversions

The dot operator (.) is used for member access. The dot operator specifies a member of a type or namespace. For example, the dot operator is used to access specific methods within the .NET Framework class libraries:

The ternary operator (?:) returns one of two values depending on the value of a Boolean expression. The conditional operator is of the form
condition ? first_expression : second_expression;
If condition is true, first expression is evaluated and becomes the result; if false, the second expression is evaluated and becomes the result. Only one of two expressions is ever evaluated.
Calculations that might otherwise require an if-else construction can be expressed more concisely and elegantly with the conditional operator. For example, to avoid a division by zero in the calculation of the sin function you could write either
// The class Console in namespace System:
System.Console.WriteLine("hello");

Thursday, 24 February 2011

Chapter 7 Selection Statements

A selection statement causes the program control to jump to another part of the program depending on a condition. Following are the selection statement available to you under C#

  1. if
  2. else
  3. switch
  4. case
  5. default

if-else statement

The if statement selects a statement for execution based on the value of a Boolean expression.
Lets check this fact out in the following example

using System;

/**
 * Author       : vblord
 * Date         : 10/03/2011
 * Description  : Check to see if the user is vegetarian or non-vegetarian and print
 *                   an appropriate message. Shows the usage of if-else
 *                
 */
namespace HelloWorld
{
    class ifelseexample
    {
        static void Main(string[] args)
        {
            Console.Write("Enter are you a vegetarian (Y/N) : ");
            char veg = char.Parse(Console.ReadLine());
            if (veg == 'Y'){
                Console.WriteLine("So you are a vegetarian, then you must love spinach");
            }
            else {
                Console.WriteLine("Aha so you are a non-vegetarian , you must like some chicken");
            }
            
            Console.ReadKey(false);
        }
    }
}


This is the output according to the user given choice

If there is more than one statement associated with the TRUE condition or FALSE condition then we must use {} to keep them in a block, because by default if only recognizes the first statement after if--elseas the statement to execute. If there is only a single line then you may or may not use the {} as per your wishes.

Nested if

Some time we require more than one condition to be true. For a statement to execute and more than one else clause. Lets look at the example below
using System;

/**
 * Author       : vblord
 * Date         : 10/03/2011
 * Description  : this is an example of nested if which firstly checks if the input 
 *                 value is an alphabet and then checks if it is lower case or uppercase
 *                
 */
namespace HelloWorld
{
    class nestedifexample
    {
        static void Main(string[] args)
        {
            Console.WriteLine("NESTED IF EXAMPLE");
            Console.Write("Enter a Any Alphabet : ");
            char c = (char)Console.Read();
            if (Char.IsLetter(c))
            {
                if (Char.IsLower(c))
                {
                    Console.WriteLine("The input is lowercase alphabet.");
                }
                else
                {
                    Console.WriteLine("The input is an uppercase alphabet.");
                }
            }
            else
            {
                Console.WriteLine("Sorry this is not an alphabet.");
            }
            
            Console.ReadKey(false);
        }
    }
}
This program asks the user for an input and the first condition to be checked is that the input should be an alphabet if it is not then it jumps to the outer else, if it is true then it checks the second if to find out the character is an uppercase or lowercase alphabet.
Sample Output 1
Sample Output 2


Sometimes nested if is not exactly what we want because there are multiple conditions to check. In such a case we can use the if-else-if structure to extend the use of this statement. Again it is much simpler to explain with the help of an example.

using System;

/**
 * Author       : vblord
 * Date         : 10/03/2011
 * Description  : this is an example of else-if construct which calculates grades of student        
                    based on his percentage
 *                 
 *                
 */
namespace HelloWorld
{
    class ifelseifexample
    {
        static void Main(string[] args)
        {
            Console.WriteLine("ELSE-IF EXAMPLE");
            Console.Write("Enter your marks in Hindi : ");
            int hindi = int.Parse(Console.ReadLine());
            Console.Write("Enter your marks in Computer : ");
            int comp = int.Parse(Console.ReadLine());
            Console.Write("Enter your marks in English : ");
            int eng = int.Parse(Console.ReadLine());
            int tot = hindi + eng + comp;
            float per = tot / 3;
            char grade=' ';
            if (per >= 90)
                grade = 'A';
            else if (per >= 75 && per < 90)
                grade = 'B';
            else if (per >= 60 && per < 75)
                grade = 'C';
            else if (per >= 45 && per < 60)
                grade = 'D';
            else if (per < 45)
                grade = 'F';
            Console.WriteLine("Total Marks are {0} your % is {1} your Grade is {2}", tot, per, grade);
            
            Console.ReadKey(false);
        }
    }
}
Sample Output
The above mentioned program calculates the total and percentage marks after accepting input of three subjects. then based on a set of conditions it gives the student a grade. In every case only one condition can be true and the student can get only one grade, some may argue this can be done by nested if but my reason for using else-if construct for this program is simplify it.

Switch statement

The switch statement is a control statement that handles multiple selections and enumerations by passing control to one of the case statements within its body . Control is transferred to the case statement which matches the value of the switch. The switch statement can include any number of case instances, but no two case statements can have the same value. Execution of the statement body begins at the selected statement and proceeds until the break statement transfers control out of the case body. A jump statement such as a break is required after each case block, including the last block whether it is a case statement or a default statement. With one exception, (unlike the C++ switch statement), C# does not support an implicit fall through from one case label to another. The one exception is if a case statement has no code. If no case expression matches the switch value, then control is transferred to the statement(s) that follow the optional default label. If there is no default label, control is transferred outside the switch.
using System;

/**
 * Author       : vblord
 * Date         : 10/03/2011
 * Description  : this is an example of switch case construct it takes a number from 1-7 and prints the
 *                 corresponding day of the week
 *                 
 *                
 */
namespace HelloWorld
{
    class ifelseifexample
    {
        static void Main(string[] args)
        {

            myDayOfWeek();
            Console.ReadKey(false);
        }

        static void myDayOfWeek()
        {
            Console.WriteLine("switch case example");
            Console.Write("Enter day of the week in numbers from 1-7 : ");
            int day = int.Parse(Console.ReadLine());
            string answer = "";
            switch(day)
            {
                case 1:
                    answer = "Monday";
                    break;
                case 2:
                    answer = "Tuesday";
                    break;
                case 3:
                    answer = "Wednesday";
                    break;
                case 4:
                    answer = "Thursday";
                    break;
                case 5:
                    answer = "Friday";
                    break;
                case 6:
                    answer = "Saturday";
                    break;
                case 7:
                    answer = "Sunday";
                    break;
                default:
                    answer = "Are you joking mate";
                    break;
            }
            Console.WriteLine("You entered {0} and the day of the week is {1}", day, answer);
            
        }
    }
}

Sample Output
These were the selection statement available to you in C#, in our next chapter we will look into few more statements provided by C#