Conditional Statements in C# .Net

Conditional Statements

Syntax of if condition :

Syntax 1 

If (condition)

Statement 1 ;

Else

Statement 2;

Syntax 2

If (condition)

{

Statement 1 ;

Statement 2;

}

Else

{

Statement 3;

Statement 4;

}

Nested If:-

If (condition)

Statement 1 ;

Else If (condition)

Statement 1 ;

Else If (condition)

Statement 1 ;

Else

.

Else

Statement;

 

Examples on if statment

A program to compare two numbers  (I and j), if I is grater change from back color  to green otherwise REO.

Open windows forms application project

arrrowPlace two textboxes and a buttonarrrow Click on button 1

arrrowCode for button 1

 

Int I = int. parse (text Box 1. text);

Int j =int. parse (text Box2.text);

If (i> j)

This. Back color = color. Green;

Else

This. Back color = color. Red;

Execute the project

Observations

What is this key ?

this is a keyword

this works like an object for current class

this will be created at run time.

this is under control of CLR.

Working with Switch condition

Switch syntax

Switch (variable)

{

Case 1:

Statements;

Break;

Case 2:

Statements;

Break;

.

Default

Statements;

Break;

}

Example on Switch condition

 

Screenshot_19

Open windows forms application project

Place a text box and a button

Code for button 1 click

 

{

Int  I = int. parse  (text box 1. text);

Switch (i)

{

….

}//switched close here

Switch (i)

{

Case 1:

This. back color = color. Green ;

Break;

Case 2 :

Color dialog c = new dialog ();

Creating an object

  1. show dialog ();

this. Back color = c. color;

break;

case 3:

Application . Exit ();

Break;

Default :

Message box . show (“enter 1,2, or 3 only”);

Break;

}// switch closed here

Execute the project

 

Observations

Syntax to create an object

Class name   (space)  obj _name = new  class name ();

 

EX:-

Screenshot_20

Color dialog is a predefined class

Application is a class which contains Exit () method

Purpose of exit () is to terminate the project