Вы находитесь на странице: 1из 32

Module 1

Namespace:

Whenever we want to group similar classes into a single entity, we can define a
namespace.

Ex:
namespace Vehicle
{
public class Car
{
//members of Car class
}
public class Bus
{
//members of Bus class
}
public class Bike
{
//members of Bike class
}
}

To create namespace objects:

using System;
using Vehicle; //note this
class Test
{
public static void Main()
{
Car c=new Car();
-------
-------
}
}
Resolving Namespace clashes:

There may be situation where more than one namespace contains the
class with same name. For example, we may have one more
namespace like –

namespace MyVehicle
{
public class Car
{
//members of Car class
}
--------
-------
}

Then to resolve this we use dot operator while creating objects:

using System;
using Vehicle;
using MyVehicle; class Test
{
public static void Main()
{
// Car c=new Car(); Error!!! name conflict

Vehicle.Car c1=new Vehicle.Car();


MyVehicle.Car c2=new MyVehicle.Car();
---------
}
Methods:

Declaring a method

The syntax for declaring a C# method is as follows:

returnType methodName ( parameterList )


{
// method body statements go here
}

Method Overloading:

Method Overloading is the common way of implementing


polymorphism. It is the ability to redefine a function in more than one
form.

Overloaded methods are differentiated based on the number and type of


the parameters passed as arguments to the methods.

Why do we need Method Overloading ?

If we need to do the same kind of the operation in different ways i.e. for different
inputs. In the example described below, we are doing the addition operation for
different inputs. It is hard to find many different meaningful names for single action.

Different ways of doing overloading methods-

Method overloading can be done by changing:

1. The number of parameters in two methods.


2. The data types of the parameters of methods.
3. The Order of the parameters of methods.

Ex:

using System;
class GFG {

public int Add(int a, int b)


{
int sum = a + b;
return sum;
}

public int Add(int a, int b, int c)


{
int sum = a + b + c;
return sum;
}

public static void Main(String[] args)


{

// Creating Object
GFG ob = new GFG();

int sum1 = ob.Add(1, 2);


Console.WriteLine("sum of the two "
+ "integer value : " + sum1);

int sum2 = ob.Add(1, 2, 3);


Console.WriteLine("sum of the three "
+ "integer value : " + sum2);
}
}

Output:
sum of the two integer value : 3
sum of the three integer value : 6

Short Circuiting using Boolean Operators:


• The && and || operators both exhibit a feature called short circuiting.

• For example, if the left operand of the && operator evaluates to false, the
result of the entire expression must be false, regardless of the value of the
right operand.
• Similarly, if the value of the left operand of the || operator evaluates to
true, the result of the entire expression must be true, irrespective of the
value of the right operand.
• In these cases, the && and || operators bypass the evaluation of the right
operand.

Here are some examples:

(percent >= 0) && (percent <= 100)

In this expression, if the value of percent is less than 0, the Boolean


expression on the left side of && evaluates to false. This value means that the
result of the entire expression must be false, and the Boolean expression to the
right of the && operator is not evaluated.

(percent < 0) || (percent > 100)

In this expression, if the value of percent is less than 0, the Boolean


expression on the left side of || evaluates to true. This value means that the
result of the entire expression must be true, and the Boolean expression to the
right of the || operator is not evaluated.

Definite Assignment Rule:

A variable must be definitely assigned at each location where its


value is obtained.

A variable must be definitely assigned at each location where it is


passed as a reference parameter.

All output parameters of a function member must be definitely


assigned at each location where the function member returns.
The "this" variable of a "struct-type" instance constructor must be
definitely assigned at each location where that instance constructor
returns.

.To String:
It converts an object to its string representation so that it is suitable for display.

using System;

public class Example

public static void Main()

Object obj = new Object();

Console.WriteLine(obj.ToString());

// The example displays the following output:

// System.Object
Precedence and Associativity:

C# if (if-then) Statement
C# if-then statement will execute a block of code if the given condition is true. The
syntax of if-then statement in C# is:

if (boolean-expression)

{
// statements executed if boolean-expression is true

The Boolean-expression will return either true or false.

If the Boolean-expression returns true, the statements inside the body of if


(inside {...} ) will be executed.

If the Boolean-expression returns false, the statements inside the body of if will be
ignored.

//you can explain in your own words

EX:

using System;

namespace Conditional
{
class If Statement
{
public static void Main (string [] args)
{
int number = 2;
if (number < 5)
{
Console. WriteLine("{0} is less than 5",
number);
}

Console. WriteLine ("This statement is always


executed.");
}
}
}
C# if...else if (if-then-else if) Statement
When we have only one condition to test, if-then and if-then-else statement works
fine. But what if we have a multiple condition to test and execute one of the many
blocks of code.

if (boolean-expression-1)

// statements executed if boolean-expression-1 is true

else if (boolean-expression-2)

// statements executed if boolean-expression-2 is true

else if (boolean-expression-3)

// statements executed if boolean-expression-3 is true

else

{
// statements executed if all above expressions are false

//Explain in your own words and example

using System;

namespace Conditional
{
class IfElseIfStatement
{
public static void Main(string[] args)
{
int number = 12;

if (number < 5)
{
Console.WriteLine("{0} is less than 5",
number);
}
else if (number > 5)
{
Console.WriteLine("{0} is greater than 5",
number);
}
else
{
Console.WriteLine("{0} is equal to 5");
}
}
}
}
Switch Case in C#

A switch case is used test variable equality for a list of values, where each value is a
case. When the variable is equal to one of the cases, the statements following the case
are executed. A break statement ends the switch case. The optional default case is for
when the variable does not equal any of the cases.

Syntax
switch(expression) {
case valueOne:
//statements
break;
case valueTwo:
//statements
break;
default:
//optional
//statements
}

Example
switch(choice) {
case 'Y' :
Console.WriteLine("Yes");
break;
case 'M' :
Console.WriteLine("Maybe");
break;
case 'N' :
Console.WriteLine("No");
break;
default:
Console.WriteLine("Invalid response");
}

Loops in C#
Looping in programming language is a way to execute a statement or a set of
statements multiple number of times depending on the result of condition to be
evaluated to execute statements. The result condition should be true to execute
statements within loops.
1. while loop The test condition is given in beginning of loop and all statements
are executed till the given boolean condition satisfies, when the condition
becomes false, the control will be out from the while loop.

Syntax:
while (boolean condition)
{
loop statements...
}

EX:

// C# program to illustrate while loop

using System;

class whileLoopDemo

public static void Main()

int x = 1;

// Exit when x becomes greater than 4

while (x <= 4)

Console.WriteLine("GeeksforGeeks");

// Increment the value of x for

// next iteration
x++;

Output:
GeeksforGeeks
GeeksforGeeks
GeeksforGeeks
GeeksforGeeks

2. for loop
for loop has similar functionality as while loop but with different syntax. for
loops are preferred when the number of times loop statements are to be
executed is known beforehand.

Syntax:

for (loop variable initialization; testing condition;


increment / decrement)
{
// statements to be executed
}

// C# program to illustrate for loop.


using System;

class forLoopDemo
{
public static void Main ()
{
// for loop begins when x=1
// and runs till x <=4
for (int x = 1; x <= 4; x++)
Console.WriteLine("GeeksforGeeks");
}
}

Output:
GeeksforGeeks
GeeksforGeeks
GeeksforGeeks
GeeksforGeeks

3. do-while loop
do while loop is similar to while loop with only difference that it checks the condition
after executing the statements, i.e it will execute the loop body one time for sure
because it checks the condition after executing the statements.

Syntax :
do
{
statements..
}while (condition);

EX:
// C# program to illustrate do-while loop
using System;

class dowhileloopDemo
{
public static void Main()
{
int x = 21;
do
{

Console.WriteLine("GeeksforGeeks");
x++;
}
while (x < 20);
}
}

Output:
GeeksforGeeks

4. while loop

A while loop statement in C# repeatedly executes a target statement as


long as a given condition is true.

Syntax
The syntax of a while loop in C# is −
while(condition) {
statement(s);
}

using System;

namespace Loops {

class Program {

static void Main(string[] args) {

int a = 10;

while (a < 20) {

Console.WriteLine("value of a: {0}", a);

a++; }

Console.ReadLine();

} } }
The break and continue statements:

The break statement is used to jump out of a switch statement also to jump out
of the body of an iteration statement.
Breaking out of a loop, the loop exits immediately and execution continues at
the first statement that follows the loop.

In contrast, the continue statement causes the program to perform the next
iteration of the loop immediately (after revaluating the Boolean expression).

EX:
C# Variables
A variable is a name given to a storage area that is used to store values of
various data types. Each variable in C# needs to have a specific type, which
determines the size and layout of the variable's memory.

Initializing Variables
Variables are initialized (assigned a value) with an equal sign followed by
a constant expression. The general form of initialization is −
<data_type> <variable_name> = value;

//Write any program with the above variables

You can write the following program example:


Exception Handling:
An exception is a problem that arises during the execution of a program.
A C# exception is a response to an exceptional circumstance that arises
while a program is running, such as an attempt to divide by zero.

Syntax:
Different type of Exceptions:
EX:
using System;

namespace ErrorHandlingApplication {

class DivNumbers {

int result;

DivNumbers() {

result = 0;

public void division(int num1, int num2) {

try {

result = num1 / num2;

} catch (DivideByZeroException e) {

Console.WriteLine("Exception caught: {0}", e);

} finally {

Console.WriteLine("Result: {0}", result);

static void Main(string[] args) {

DivNumbers d = new DivNumbers();

d.division(25, 0);

Console.ReadKey();

}
PROGRAMS TO STUDY:
Factorial using Recursion:

Output

Value is : 362880
Largest of 3 numbers:

//write your own output


FIBONACCI SEREIS:
1. using System;
2. public class FibonacciExample
3. {
4. public static void Main(string[] args)
5. {
6. int n1=0,n2=1,n3,i,number;
7. Console.Write("Enter the number of elements: ");
8. number = int.Parse(Console.ReadLine());
9. Console.Write(n1+" "+n2+" "); //printing 0 and 1
10. for(i=2;i<number;++i) //loop starts from 2 because 0 and 1 are already printed

11. {
12. n3=n1+n2;
13. Console.Write(n3+" ");
14. n1=n2;
15. n2=n3;
16. }
17. }
18. }

Output:

Enter the number of elements: 15


0 1 1 2 3 5 8 13 21 34 55 89 144 233 377
Arithmetic Operations (Addition, Subtraction.
Etc):

O/P:
Operators in C#:

Вам также может понравиться