Sei sulla pagina 1di 41

Introduction to C#

Shubhangi Shinde

Introduction
CSharp is an Object Oriented Language , introduced in the
.NET Framework. C# is a professional programming
language and is very similar to C++ in many ways. We can
implement the Object Oriented concepts
like encapsulation, inheritance, and polymorphism in C#
programming development .
C# is a Simple, Powerful , general-purpose and Type-Safe
language also Case Sensitive . We can develop C# projects
in Visual Studio Environment , a powerful tool-rich
programming environment from Microsoft. We can create
console based applications as well as windows based
applications from C# environment. C# Coding style is very
similar to C++ and JAVA , so the developers who are
familiar with those languages can pick up C# coding quickly.

C# and JAVA
Classes in C# are descended from System.Object Class
and in JAVA all classes are subclasses
of java.lang.Object Class.
C# source codes are compiled to Microsoft Intermediate
Language (MSIL) and during the execution time runs it
with the help of runtime environments - Common
Language Runtime (CLR). Like that JAVA source codes
are compiled to Java Byte Code and during the
execution time runs it with the help of runtime
environments - Java Virtual Machine (JVM). Both
CSharp and JAVA supports native compilation via Just
In Time compilers.

C# Data Types
C# is a strongly typed language. It means, that
you cannot use variable without data types. Data
types tell the compiler that which type of data is
used for processing.
C# provides two types of data types: Value
types and Reference types.
A Value type data type stores copy of the value
whereas the Reference type data types stores the
address of the value. C sharp provides great
range of predefined data types but it also gives
the way to create user defined data types.

Value Types
Data Types

Size

Values

sb yte

8 bit

-128 to 127

b yte

8 bit

0 to 255

short

16 bit

-32,768 to 32,767

ushort

16 bit

0 to 65,535

int

32 bit

-2,147,483,648 to 2,147,483,647

uint

32 bit

0 to 4,294,967,295

long

64 bit

-9,223,372,036,854,775,808 to 9,223,372,036,854,775,807

ulong

64 bit

0 to 18,446,744,073,709,551,615

char

16 bit

0 to 65535

float

32 bit

-1.5 x 1045 to 3.4 x 1038

double

64 bit

-5 x 10324 to 1.7 x 10308

decimal

128 bit

-1028 to 7.9 x 1028

bool

---

True or false

Reference Types:
Data Types

Size

Values

string

Variable length

0-2 billion Unicode


characters

object

---

---

C# Operators
Operators are very useful thing in computing
value. While writing a program, you need
various types of operators to calculate value.
Results are computed by building expressions.
These expressions are built by combining
variables and operators together into
statements.

Arithmetic Operators:
Operator

Description

Examples

Add numbers

X=num1+num2

Subtract numbers

X=num1-num2

Multiply numbers

X=num1*num2

Divide numbers

X=num1/num2

Divide two numbers and returns reminder X=22%10 then X will be X=2

C# Assignment Operators
Assignment Operators Usage

Examples

= (Equal to)

result=5 Assign the value 5 for result

+= (Plus Equal to)

result+=5

Same as result=result+5

-= (Minus Equal to)

result-=5

Same as result=result-5

*= (Multiply Equal to)

result*=5

Same as result=result*5

/= (Divide Equal to)

result/=5

Same as result=result/5

%= (Modulus Equal to) result%=5 Same as result=result%5

C# Command Line Argument


Parameter(s) can be passed to a Main()
method in C# and it is called command line
argument.
Main() method is where program stars
execution. Main method doesnt accept
parameter from any method. It accept
parameter through command line. It is an
array type parameter that can accept n
number of parameter in runtime.

using System;
namespace command
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("First Name is " + args[0]);
Console.WriteLine("Last Name is " + args[1]);
Console.ReadLine();
}
}
}

if else constructs
The if else construct is used for determining
the flow of program based on returning
expression value. It evaluates the comparison
operator and based on value executes the
statements.

switch case constructs


Switch case is also another condition
constructs in C# programming that evaluates
the condition as if else but only difference is
that it makes program simpler and easier. It is
used when there is multiple if condition in a
program. It also includes a default value in
Default statements. If no any case matches
then Default statements executes and run the
code.

Guideline to use Switch case:


1. Must include break statement in each case and
default statements.
2. If you are accepting char value then write it
within single quotes as follow:
case 1, case b, case c, case k etc.
3.If you are accepting string value then write it
within double quotes as follow:
case add, case sub, case mul, case div etc.

C# Branching Statements
Branching
statement

Description

break

Leaves the switch block

continue

Leaves the switch block, skips remaining logic in enclosing loop, and goes back to loop condition to determine if
loop should be executed again from the beginning. Works only if switch statement is in a loop as described
in Lesson 04: Control Statements - Loops.

goto

Leaves the switch block and jumps directly to a label of the form "<labelname>:"

return

Leaves the current method. Methods are described in more detail in Lesson 05: Methods.

throw

Throws an exception, as discussed in Lesson 15: Introduction to Exception Handling.

Goto Statement
The goto statement is a jump statement that
controls the execution of the program to
another segment of the same program. You
create label at anywhere in program then can
pass the execution control via the goto
statements.

using System;
namespace goto_statement
{
class Program
{
static void Main(string[] args)
{
string name;
label: //creating label with colon(:)
Console.WriteLine("Enter your name:");
name = Console.ReadLine();
Console.WriteLine("Welcome {0}", name);

goto label; //jump to label statement

C# Break Statement
The break statement is used to terminating
the current flow of program and transfer
controls to the next execution.

using System;

namespace break_statement
{
class Program
{
static void Main(string[] args)
{
int i = 0;

while (i < 100)


{
Console.WriteLine(i);
if (i == 20)
{
Console.WriteLine("breaking the current
break;
}
i++;
}
Console.ReadLine();

segment...");

C# Continue Statement
The continue statements enables you to skip
the loop and jump the loop to next iteration.

using System;
namespace Continue_Statement
{
class Program
{
static void Main(string[] args)
{
int i = 0;
while(i<10)
{
i++;
if (i < 6)
{
continue;
}
Console.WriteLine(i);
}
Console.ReadLine();
}
}
}

Control Statements - Loops


The loop constructs is used to execute
a block of code until the condition becomes
expired
while loop.
do loop.
for loop.
foreach loop.

While Loop

three things are important.


(i) Initialization
(ii) Increment/Decrement
(iii) Termination

using System;

namespace While_Loop
{
class Program
{
static void Main(string[] args)
{
int num1,res, i;
Console.WriteLine("Enter a number");
num1 = Convert.ToInt32(Console.ReadLine());

i = 1; //Initialization
//Check whether condition matches or not
while (i <= 10)
{
res = num1 * i;
Console.WriteLine("{0} x {1} = {2}", num1, i,
i++; //Increment by one
}
Console.ReadLine();

res);

do While Loop
do while loop treats same as while loop but
only differences between them is that, do
while executes at least one time. The code
executes first then check for specified loop
condition.

using System;
namespace do_while
{
class Program
{
static void Main(string[] args)
{
int table,i,res;
table=12;
i=1;
do
{
res = table * i;
Console.WriteLine("{0} x {1} = {2}", table, i,
i++;
}
// must put semi-colon(;) at the end of while
do...while loop.
while (i <= 10);

Console.ReadLine();

res);
condition in

C# for Loop
A for loop works like a while loop, except that the
syntax of the for loop includes initialization and
condition modification.
for loops are appropriate when you know exactly
how many times you want to perform the
statements within the loop.
The contents within the for loop parentheses
hold three sections separated by
semicolons (<initializer list>; <boolean
expression>; <iterator list>) { <statements> }.

using System;
namespace for_loop
{
class Program
{
static void Main(string[] args)
{
int i;
for (i = 0; i < 5; i++)
{
Console.WriteLine("For loop Example");
}
Console.ReadLine();
}
}
}

Nested for loop


A loop within a loop is called nested loop. You
can nested n number of loop as nested.

using System;

namespace nested_loop
{
class Program
{
static void Main(string[] args)
{
int i, j;
for (i = 1; i <= 5; i++)
{
for (j = 1; j <= i; j++) //Nested for loop
{
Console.Write(j);
}
Console.Write("\n");
}
Console.ReadLine();
}
}
}

foreach loop
A foreach loop is used to iterate through the items in a list.
It operates on arrays or collections such as ArrayList, which
can be found in the System.Collections namespace.
The syntax of a foreach loop is foreach (<type> <iteration
variable> in <list>) { <statements> }.
The type is the type of item contained in the list. For
example, if the type of the list was int[] then the type
would be int.
Syntax
foreach (string name in arr)
{
}

using System;

namespace foreach_loop
{
class Program
{
static void Main(string[] args)
{
string[] arr = new string[5]; // declaring array
//Storing value in array element
arr[0] = "Steven";
arr[1] = "Clark";
arr[2] = "Mark";
arr[3] = "Thompson";
arr[4] = "John";

//retrieving value using foreach loop


foreach (string name in arr)
{
Console.WriteLine("Hello " + name);
}
Console.ReadLine();

Function Parameter in C#
There are two type of function parameter in
C#, Value type parameter and reference type
parameter.

using System;

Value type

namespace Value_Type
{
class Program
{
public static int qube(int num)
{
return num * num * num;
}
static void Main(string[] args)
{
int val,number;
number = 5;
//Passing the copy value of number variable
val = Program.qube(number);
Console.Write(val);
Console.ReadLine();
}
}
}

Reference variable

using System;

namespace Reference_Parameter
{
class Program
{
public static void qube(ref int num)
{
num = num * num * num;
}
static void Main(string[] args)
{
int original = 9;
Console.Write("\ncurrent value of Original is

Program.qube(ref original);
Console.WriteLine("\nNow the current value of
{0}\t", original);
Console.ReadLine();
}
}
}

{0}\t", original);
Original is

C# out parameter
C# out parameter is such type of parameter that is
declared with out keyword. It is the same as reference
parameter, that doesnt create memory allocation.
Usually, a method returns value with return keyword.
Unfortunately, a return modifier can return only one
value at a time. Sometime, your C# program required
to return multiple values from a single method. In this
situation, you need such type of function that can
produce multiple output result from a single function.
The output parameter C# lets your program to return
multiple values.

using System;

namespace out_parameter
{
class Program
{
//Accept two input parameter and returns two out value
public static void rect(int len, int width, out int
area, out int perime
ter)
{
area = len * width;
perimeter = 2 * (len + width);
}
static void Main(string[] args)
{
int area, perimeter;
// passing two parameter and getting two returning
value
Program.rect(5, 4, out area, out perimeter);
Console.WriteLine("Area of Rectangle is {0}\t",
area);
Console.WriteLine("Perimeter of Rectangle is
{0}\t",
perimeter);
Console.ReadLine();
}
}
}

Potrebbero piacerti anche