Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
11 views

Programming Basics in C# v3

Uploaded by

nani031nani
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

Programming Basics in C# v3

Uploaded by

nani031nani
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 93

what is Microsoft dotnet [.

Net]

.net is a software platform.


Every Software platform contains Languages &
Technologies.
where to start .net learning

language? technology?
Recall your child hood days?
tell me your education started with a language or
subject?

we started our education with language (english | hindi | …)

we can’t read or learn physics subject written in english


without knowing english
languages & technologies
supported in .net
languages technologies
c# (csharp) asp.net
vb.net asp.net mvc
c++.net ado.net
jscript.net wcf
…….. ……..
70+

do we need to learn all languages? no


C# Learning Sequence

data types conditions


class
arrays
object loops

method
structures
RAM

RAM

understand RAM is important for becoming a programmer

since all software code will be finally executed in RAM


data type
what ?

it is a place for storing data

this box is now a

79 data type ( since it


is storing data )

tip we can call any thing as data type if it is storing data


In real time world we will see

Fixed size containers Varying size containers

1ltr Water bottle

baloon

1 kilograms

same way in c# language also we have fixed size datatype and arying size datatype
Types of data types

Fixed size data type Varying size data type


string
Datatype Size array
long 8bytes class
Object class
ulong 8bytes
interface No limit
int 4bytes Integral datatype delegate
uint 4bytes enum
short 2bytes struct
ushort 2bytes Integral datatypes can store only plain numbers not
decimal numbers Ex: 10 ,88..
byte 1byte
Note:
sbyte 1byte char datatype is a special integral datatype in which we
char 2bytes can store any single character
bool 1bit Can store either true or false
float 4bytes
double 8bytes floating point data types (can store decimal values)
decimal 16bytes
un-signed data types
the data types which can store only +ve values
are called as un-signed data types
Datatype Size
-+ long 8bytes

+ ulong 8bytes

-+ int 4bytes

+ uint 4bytes

-+ short 2bytes

+ ushort 2bytes

+ byte 1byte

-+ sbyte 1byte
using data types
datatype name= data;
req: I want to store age of a person (20) RAM
int age=20; age

Console.WriteLine(age); 20
30 4 bytes

Is it possible to change data in the data type


age=30;
correct way of typing code in VS
int age=20;
rules while using c# data types
• for using any datatype we write
datatype variablename = value;
• the above rule will not work some data types like
char can store only one char ( any char present in key board )
char data must be stored in single quotes
Datatype

char
c
*
& 2 bytes
bool

float

decimal

string y
10.75 4 bytes
decimal can store decimal value
we must place m after decimal
Datatype
c
char
16 bytes 800000000.76
bool

float

decimal

string
string can store 0 or more values ( any type
of chars supported in key board )
y
10 bytes palle
data type conversion
1. implicit copying 2. explicit copying dt1 dt2
i j
10 10
x y
10 10
3. copying data using Convert class methods
Writing code in visual studio
Open visual studio any version

---------------
C# code
---------------
class
Class is a virtual entity or a model or a template or a blue print.

Class Syntax:
public class A
access_specifier class classname
{
{
------------;
c# Code
------------;
----------variables-------; ------------;
----------methods-------;
} }

NOTE
1. we usually use public as access specifier
2. c# statements must end with semicolon
Where to write class in C#
Tell me where will you write a class
Namespace
How many classes can be written in a NS?
Let’s see a sample -- -- - -
Assume we have created a new console application Class - -- -
with the name sample
Class1 Class2

Class before Program class?


It is not recommended
Class within Program class?

Class within main method?

Class after Program class?

Class after NameSpace?


Class Sample-1

Create a class for storing person details


Maya

25

person Bangalore
Class-Lab1
Create a class for storing professor details

Madhav

40
Computerscience

professor M-tech
program entry and exit point
Assume there is one house
with multiple room
How will you enter into the room?
How will you come out of the house
Again through MainDoor

Similarly ,In Csharp main method is entry and


exit point for the Program execution.

Main door Room1 Room2

program execution will start and end at main


method
class as virtual entity

CLR

RAM

x 2bytes

10 4bytes
object

object is a physical entity or a real world entity


Syntax:
classname variablename = new classname();

Used to create object


Creating object sample

LHS RHS How to print the data in object


CLR RAM

Responsible for creating object d Doctor


Class name
age exp
36 8

name
dr.sachin
reading & modifying object data

How to print the data in object


RAM

d Doctor

age exp
36 8

name
dr.sachin
simple & complex data types
Data types

Simple data complex data

complex data type

Simple data type x(variable)


10 Int : 4 bytes d

D name age
o
c dr.sachin 36
t exp
o
r 6

RAM MEMORY

d.age=34
objects assignments

• Create object of nurse class in main method display


data present in nurse object
Name:vani
Nurse class Qualification:Bsc nursing
Age:26

• Create object of patients class in main method


display data present in patientsobject
Name:suleman

Age:79
Bg:O+ve
Patient class Disease:Viral fever
methods
• using methods we can do work (or) perform action.
• using variables we can store data.
programmer can given any
syntax : name to the method

access_modifier return_type method_name( dt vn1 , -----)


{
-------------- 
--------------
} c# datatype
Parameter list.
access modifier return type As per industry standard ,
take max 4 parameters.
public data type
-------- (or)
-------- void void variable;

types of methods
Input
 Output  No Output
No Input
C# Method C# Method

Input
 No Output
 Multiple Output

C# Method No Input
C# Method

No Input  Output we cannot write multiple return types in


C# Method a single method. (or) we cannot return
multiple values in a single method

We have to understand the structure


Where will you write a method in c# program of the C# program
structure of c# program
always create class
in namespace
always create
methods in class

NameSpace
class1
Class
-
Method Method1 class2

Methods2 Methods3
class3

-- ---- ---- ---- --- --- ---- --

---- - ------- ------ --- --


method declaration sample 1
Req: declare a method with name m1 in Class A which accepts string
and int datatypes as input and returns char datatype as output

- There is alternative
way for returning
string data
char OR
int m1

Class A

returning variables data type and


return type must match
method declaration sample-2
Req1: declare a method (m2 in class B)which accepts string ,bool
datatypes as input and returns float as output,
Req2: declare another method (m3 in class B) which accepts char
datatype as input and return long as output

string float
-
bool m2

char
long
m3

Class B

What will be the return type


What data has to be returned
What will be the return type
method declaration sample 3
Req: declare a method(m4 in Class D) which accepts int and
float datatypes as input and returns no output

int
no data will be returned
float m4

Class D
can’t write return when the
return type is void
method declaration sample 4
Req1: declare a method (m5 in class F) which accepts no input
and returns int data as output
Req2:declare another method(m6 in class F) which accepts no
input and returns no output

- int
m5

m6

Class F
calling methods

CLR

Output

suresh 34

$
calling methods sample2
calling methods sample 3 ( void return type )

10 20

You cannot use return keyword


if your method returnType is void

 Void type variables


are not supported
calling methods sample4

10 20

10 + 20

10 20

10 - 20

result1 30

result2 -10
calling methods lab

Call the methods by passing appropriate parameters


naming conventions used in c#

• we must use proper naming conventions while


creating real time applications.
• naming conventions will improve code readability
and maintainability
• In general while creating .net applications companies
will follow either
• pascal casing convention(every word start with capital letter)
• camel casing convention(all chars in first word must be lower
case and from second word pascal casing rules are applicable)
example for pascal and camel
naming conventions
Req:
write patientbeddetails in pascal and camel naming conventions
pascal casing convention:
PatientBedDetails

camel casing convention:


patientBedDetails
where to use pascal & camel
naming convention
Use Pascal naming when you are giving
• SolutionName
• ProjectName
• FileName
• ClassName
• MethodName
• InterfaceName
• DelegateName
• structName
• GlobalVariableName
use camel naming conventions :
• while declaring local variables
naming standards

• while implementing real applications it is


recommended to use good naming standards.
• use complex noun for naming class
• use simple noun for naming variable
• use verb for naming method

complex
simplenoun
nounwill
willhave
not have
sub properties
sub properties
( ex Doctor
( ex
verb Is a representation of action
 will have name, cellnumber
age, exp, qualification,
) etc..
naming standards Lab
Identify which of the following can be used as a
class, method and a variable?
• Add
• Person
• Name
• Age
• DateOfBirth
• BloodGroup
• Doctor
debugging

• Using debugging programmers can


understand code execution sequence
• using debugging technique we can understand
the logic writing by other programmers.
• debugging will allow us to identify problem
locations in the code.
debugging sample

Trainer Note: show debugging


directly in vs
Debugging 2

left click with mouse on cement


colored wall to insert break point.
conditional statements
we must use conditional
statements for executing a
piece of code based on
result of a condition.
conditional statements syntax
syntax : what is boolean expression???

if ( boolean expression ) An expression which will give either true or false


{
---------
}
else if ( boolean expression )
{
---------- we can write 0 or more
} else if statements
….
…..
else
{ we can write 0 or 1
--------- else statement
}
conditional statements rules

Whether it will work or not ?


Do you think that this code will work? 



conditions sample 1
Req: print data based on x values.
20 ;
10
10
100
14
14 10 Hai 14 Hello 20 Bye
if it is some thing else print welcome
Hai

Hello

Bye

Welcome
conditions sample 2
Req:Write Conditional statement for printing Hello if ‘a’ value is
greater than 10 or print Hai.
25 Assume User Gives value of ‘a’ variable as 25
25 >10 True
a>10

OUTPUT

Hello
conditions sample 3
print one two three…
based on fruit names
apple one
banana two
mango three
…….. four
conditions sample 4
Req: If the user gives the value
Assume I have declared a character variable
for the character variable as
‘B’ A then print Apple
B then print Boy
False C then print Cat
If any other character then
print Orange

True

The user has given the input as B

OUTPUT
Boy
bool variable conditions part 1
Req:Assume i declared a bool variable b1, if b1 is true print hi
bool b1= true
true

true
short hand way to write this code is
bool variable conditions part 2
Req:Assume i declared a bool variable b2, if b2 is false print hello
bool b2= false
false
nested conditions
Is it possible to have if , else if and else statements within another else
if statement
if statement
statement? ??

 YES
 YES
 YES

0 or more else if

0 or 1 else
0 or more else if
0 or 1 else
and table or table
T && T T
F && T F
T && F F
F && F F
T || T T
F || T T
T || F T
F || F F
using multiple expressions
in conditional statements – 1
If(1expression) { ….. }
If(exp1 && exp2)
{
If exp1 and exp2 both are true, execute
----c# code---- the body
} Use conditional and (&&) operator
If(exp3 || exp4)
If any one of the expression is true ,execute
{ the body
----c# code----
Use conditional or(||) operator
}
conditional statement lab
Req:
1.Create a class named Days
2.create a method GetDayName in Days class
3.GetDayName method must take dayNo as input
4. GetDayName must return dayName as string
public string GetDayName(int dayNo)
{ Trainer : ask students to write
…your code here … code & trainer must monitor
verify the same day
}
Note: return Monday to Sunday if values atre 1,2,..7
if any other number is passed as input return invalid day
If..elseif..else-Lab
* Create a Fruitshop class.
* Create a method GetTotalCost (string fruitName,int qty).
* Method return type must be int.
Conditions:
Description If Qty Purchased Cost
If fruit is Apple Qty>10 12
If fruit is Apple Qty<=10 15
If fruit is Orange Qty>20 7
If fruit is Orange Qty>10 && Qty<=20 8
If fruit is Orange Qty<=10 9
switch

switch case is usually faster than series of if


and else if statements.
It is better to use switch statement when
more than one else if statement is present in
a conditional statement.
switch syntax
Syntax:
switch(existing variablename or expression)
{
case predicted value1:
-------- create 10 case labels if we have
-------- 10 predicted values
break;
case predicted value2:
--------
-------- all case & default labels must end with
break; break;
……………………..
……………………………….
default:
-------
-------
break; default is compulsory for switch case.
}
switch statement-sample

Req:1.Create a Days class


2.Within class create a method GetDayName
3.If you pass day number to the
GetDayName(),it must be able to return the day
name.
output
RAM Architecture
we know that all the programs are executed in RAM memory

Stack ( local variables )


when we start our computer
the OS will divide the RAM into
22-23 partitions Heap ( objects & arrays )
Operating System

Code Segment (methods )


As a programmer we need to
understand 4 partitions Data Segment ( static variables )

String Buffer/String pool (strings )

RAM
variables

Global variable(Field/Data member) Local variable


variable declared in class body variable declared in method header or body

Which kind of variable called as Global variables?

Which kind of variable called as Local variables?


memory allocation
• All Local variables are stored in Stack.
• All Class Objects are created in Heap.
• All Global variables are created in Object.
• All the methods are loaded in the code segment
S d
t
a 0x100 D
c
Local variable k Starting address 0x100
….D
10 H o
e
Palle b an x y
a
p
j 10 Palle
D
Global variable Ending address 0x150
Code segment
Arrays
Arrays:
Array is a collection used for storing
logically related multiple values under a single
variable name
Syntax:
DT[] VN= new DT[size]{v1,v2,v3………};
purpose of arrays
• Using arrays we can store multiple values under
a single variable name.
• Usually, to store 3 professors name ,we will declare
three variables profname1 18 bytes
dr.suresh 18 bytes R
profname2 18 bytes
Incorrect
dr.veena 16 bytes
A
approach
profname3 18 bytes M
dr.dappu 16 bytes
• For storing single variable name profname1 it requires 9*2 bytes
same way for storing all profname variables it takes huge memory

Using arrays
reading & modifying arrays data
profnames
0x200 string[]

How to print data present in array??????

0X200
To retrive 1st cell data dr.suresh dr.veena
dr.sachin dr.dappu
0 1 2
To retrive 2nd cell data

to modify 2nd cell data:


To retrive 3rd cell data
declaring empty arrays

To store data in empty array nos


0x200 int []

0X200
40 56 87

0 1 2
array assignment
1. Declare char[] array to store $ ! # @
2. Declare bool[] array and store true ,
false , true , false
3.Declare float[] array for storing
• 10.78f 14.678f 19.21f 7.989f
loops
loops are used for eliminating
code repetition (or) code duplication

c# supports
• for loop
• for each
• while loop
• do-while loop
• In this tutorial we will learn only for loop
for syntax
FALSE
TRUE
for ( Initialization; Condition; Increment/decrement )
{
Returns either TRUE or FALSE
repeating unit of code Assume condition is false
}
Importance of Loop
Req: Display all items present in
Raj Hari suresh kiran
the array names
Index numbers 0 1 2 3
Using loops , we can reduce the logical code duplication
+1
Starting value

+1

+1
Ending value
Current i value Condition
Which are starting and ending values Raj
i=0 0<=3 T
i=1 1<=3 T Hari
i=2 2<=3 T suresh
i=3 3<=3 T kiran
i=4 4<=3 F
End of Loop
loops sample 1

10 11 14 26
Index numbers 0 1 2 3

Req: Display all items present in the array in reverse order

Current i value Condition Output

j=3 3>=0 T 26
j=2 2>=0 T 14
j=1 1>=0 T 11
j=0 0>=0 T 10
j = -1 -1>=0 F

End of Loop
loop sample 2 num
10 7 9 5 4 100 99
Index numbers 0 1 2 3 4 5 6
Req: Display alternate array items present in the array

Current i value Condition output


i=0 0<=6 10
i=2 2<=6 9
i=4 4<=6 4
6<=6 99
i=6 8<=6
i=8

End of Loop
Consider this array
Loop sample 3 Expected output:

22 22
Index no 0 1 2 3 4 5 6 7 8 9 11 11
44 44
33 33
i 66 66
False 55 55
CLR 1 88 88
3 77 77
5
7 111 111
End of the Loop 99
9 99
Find the logic. 11
+2
Let us forget the even numbers,
+2 just for finding the logic.
Is there any logical relation between
+2 these numbers? Yes
Which are starting and ending numbers?
+2
How will you print the other numbers?
LOOPS O/P
Req: Print the numbers like this 1
+1
2
+1
3
+1
4
Current i value Condition +1
5
i=1 1<=6 T 1
+1
i=2 2<=6 T 2 6
i=3 3<=6 T 3
i=4 4<=6 T 4
i=5 5<=6 T 5
i=6 6<=6 T 6
i=7 7<=6 F End of loop
recursion
A function calling itself is called as recursion.
recursion used as an alternative for loops

Output is:
1
2
3
4
5
6
Recursion Assignment
Find the factorial of a given number by using
recursion

OUTPUT: 720
pre and post Incrementation
• Usually pre and post incrementation statements will
work similar except in one case.
• We can observe diff between pre and post
incrementation when these statements are clubbed
with other statements.
• X++  X=X+1; (Post Incrementation)
• ++Y  Y=Y+1; (Pre Incrementation)
• Pre incrementaion statement is a high priority
statement.
• Post Incrementation statement is a low priority
statement.
pre increment and post increment

?
?
Preincrement and post increment-Assignment

What Is the output


project 1
1. Create a class with the name Billing

2. Create a method with the name GenerateBill


3. GenerateBill must take units consumed as input and return the
bill based on the slab system
4. pass the units by taking value from console ( use
Console.ReadLine() for taking input )

No of units consumed Cost per unit in rupees


0-50 5
51-150 7
151-250 12
>250 15
strings
• strings are considered as character arrays and also
immutable entities(whose content is not changeable)
• strings are always stored in string buffer
LHS RHS Stack s
0x100 string

Heap
Req: I want to print each character in
string

p String Buffer 0x100


a
p a l l e
l 0 1 2 3 4
l
e
output
difference between string and
character array

s[1]=‘Z’; Stack
c s
c[1]=‘Z’; 0x200 Char[] 0x100 string

Heap 0x200
p a l l e
0 1 2 3 4

String Buffer 0x100

p a l l e
0 1 2 3 4
String rules
Rules while declaring strings in c#
string s=“__________”;

English char,numbers,special char,escape char/except non escape char


Few string samples:



escape characters in c#
Escape descriptions/meaning
chars
\a Bell alert sound
\t Horizontal tab(5 spaces)
\n For print in new line
\’ ‘
\” “
\? ?
\\ \

We will see the effect of escape characters while printing the data
escape characters samples
Output:
palle
tech
Output:
palle tech

5 spaces
Output:
palle\tech

Output:
p”all”e
verbatim string(@)
1.String starting with @ is known as verbatim string ,
2.all char present in double quotes are treated as normal char in
case of verbatim strings
Req:I want to print a path Why I am getting error
Since \p is not escape char

Is there any way to print path as it


is

Is there any way to print path as it is


Using @ before string,all char are treated as normal char

Output:
E:\palle\beststudents.txt
strings and immutability
• Strings are considered as immutable entities(whose content is
not changeable) since they are stored in string buffer.
LHS RHS
s
Stack 0X800
0X600 string

Req:I want to add new string to


existing string
Heap

0X600
P a l l e t e c h
0 1 2 3 4 5 6 7 8

0X800
p a l l e t e c h
0 1 2 3 4 5 6 7 8
strings & immutability assignment
Consider I have declared a string variable like this RAM
Stack
s
0x600
0x300
0x200
0x100 String

H
e
a
p
S 0x200
t p a l l
r 0x100
I 0 1 2 3
p a
n 0x300
g 0 1
p a l l e
B
u 0 1 2 3 4
0x600
f
f p a l l e t e c h
e 0 1 2 3 4 5 6 7 8
r

You might also like