Beruflich Dokumente
Kultur Dokumente
Agenda 1. 2. 3. 4. 5. 6. 7. 8. 9. Table Of Contents P RIMITIVE D ATA T YPES AND V ARIABLE D ECLARATION V ARIABLE D ECLARATION S YNTAX H ANDLING O VERFLOW C HECKS C AST ING BETWEEN OTHER DA TA TYPES B OXING & U NBOXING E NUM AND C ONSTANT O PERATORS C ONTROL S TATEMENTS W ORKING WITH A RRAYS W ORKING WITH M ETHODS Primitive Data Types and Variable Declaration Handling Overflow Checks Casting between other data types Boxing & Unboxing Enum and Constant Operators Control Statements Working with Arrays Working with Methods
Language Basics
Chapter-3
3 5 6 8 9 10 11 12 18 22
Language Basics
Chapter-3
Language Basics
Chapter-3
* Even though the decimal datatype as decimal point its not floating because the number of digits after decimal are fixed i.e. 28 digits. Other DataTypes: Char 2 System.Char Uses Unicode Charset and thus supports multiple languages string ** bool object ** 1 Systring.String System.Boolean System.Object Uses Unicode Charset True / False Generic Datatype
**All the above data types are Value Types except String and Object, which are Reference Why Data types: Based on the data type the size of variable and the format in memory is decided Based on the data type the compiler is going to validate the expressions making the language type safe. Memory in an application is divided into three parts. 1. Global Memory: Used by all global variables. These variables are allocated memory when the application begins and will remain in memory throughout the life of the application.
Language Basics
Chapter-3
Stack Memory: Used by local variables of a method. When a method is invoked a stack of memory is allocated to and the stack is cleared when the method returns
3.
Heap Memory: All dynamic memory requirements of an application are fulfilled from the heap memory. After allocating some memory from heap to a variable, once its job is completed the memory must be returned back to heap so that the same can be reused for another variable.
The value type of variable has value where as the value of a reference type is reference to value (object) on heap.
The value (object) of a reference type is always allocated heap memory. Value types are allocated memory based on the scope of the variable, If its Global Variable its allocated memory in Global Memory Area, if its Local Variable or Parameter its allocated memory on stack and if its a member of an object its allocated memory on Heap.
Value Types directly hold the value. Ex: All Basic Types, Structures & Enum Reference Types hold the reference to the value on HEAP. Ex: String, Object, Class, Arrays, Delegates
ValueType
Var = Value
Value
Language Basics
Chapter-3
Casting: Converting data from one form to another form. If RHS expression and LHS variable are not of same data type then casting is required. Casting can be implicit casting or explicit casting. Implicit Casting: If every possible value of RHS expression is valid for a variable on LHS variable. Explicit Casting: If an RHS expression is assigned to LHS and if there is a possibility of data loss then explicit casting is needed. Program to caste integer to byte using System; class Program { public static void Main() { int n = 256; byte b; byte b1, b2, b3; b1 = b2 = 10; //In VB it is not valid b1 = b2 + b3; //Compilation Error //if either byte, short or char variables are used in an expression they are automatically raised to the rank of int. b1 = (byte)(b2 + b3); } } Code: 3.1 C#
Language Basics
Chapter-3
Code snippet for handling overflow checks unchecked //Overflow checks are not done { b = (byte) n; Console.WriteLine(b); } checked //Overflow checks are done { b = (byte) n; Console.WriteLine(b); } To Enable / Disable Overflow checks: Project Properties Compile Scroll and Click on Advanced Compile Options Check Integer Overflow Checks
Fig: 3.1
Language Basics
Chapter-3
Note: You cannot use the checked and unchecked keywords to control floating point (non-integer) arithmetic. The checked and unchecked keywords control only integer arithmetic. Floating point arithmetic never throws OverflowException. Converting float & decimal datatypes double dbl = 0.6D; //0.6 float f = 0.6F; decimal dec = 0.6M; //long to float - Same as VB long lng = 10L; f = lng; //because range of long is smaller than float lng = (long) f; //float and decimal requires casting dec = 10; //Integer to decimal //f = dec; //Invalid //dec = f; //Invalid f = (float) dec; dec = (decimal) f; //decimal should be explicitly casted to every other type if required.
Language Basics
Chapter-3
Language Basics
Chapter-3
Language Basics
Chapter-3
10
Language Basics
Chapter-3
Operators
Arithmetic
Logical
Operators
Ternary
Operator
String
concatenation
Increment,
decrement
Bitwise
Relational
Assignment
Type
information
Indirection
and
Address
Dividing
a
Integral
Type
with
zero
(Integral
Division
Operator)
throws
DivideByZeroException
Floating
Point
Division
by
zero
is
not
a
runtime
exception
but
the
value
would
be
either
PositiveInfinity
(if
numerator
is
greater
than
zero)
or
NegativeInfinity
(if
numerator
is
less
than
zero)
or
NaN
(if
numerator
is
also
zero)
Using
Conditional
operator
n
=
10;
int
m
=
n++;
//m=n;
n=n+1
-
Post
Increment
Console.WriteLine(n
+
"
"
+
m);
m
=
++n;
//n=n+1;
m=n
-
Pre
Increment
Console.WriteLine(n
+
"
"
+
m);
//?:
Conditional
Operator
(VB:
IIf)
int
max;
max
=
n
>
m
?
n
:
m;
//?:
Operator
+,
-,
*
,
/
,
%
(mod)
(Power
operator
is
missing)
^
(XOR),
!(NOT)
&&
(VB-AndAlso)
,
||
(VB-OrElse)
?:
+
(VB-&)
++
,
--
<<
,
>>,
&
,
|
,
~
(complement/negation)
=
=
,
!=
,
<
,
>
,
<=
,
>=
=
,
+=
,
-=
,
*=
,
/=
,
%=
,
&=
,
|
=
,
^=
,
<<=
,
>>=
is
,
sizeof
,
typeof,
as
*
,
->
,
[]
,
&
11
Language Basics
Chapter-3
Co ntrol
Statements
If
else-statement
syntax:
if
(BooleanExpression)
{
statement;
}
else
if
(Boolean-Expression)
{
statement;
}
else
{
statement;
}
Program
to
print
if
the
command
line
argument
provided
is
an
odd
number
or
even
number
using
System;
using
System;
class
Program
{
public
static
void
Main(string[]
args)
{
int
n;
if
(args.Length
==
0)
Console.WriteLine("Please
provide
a
number");
else
if
(!int.TryParse(args[0],
out
n))
Console.WriteLine("Not
a
number");
else
if
(int.Parse(args[0])
%
2
==
0)
Console.WriteLine("Even
number");
else
Console.WriteLine("Odd
number");
}
}
Code:
3.3
C#
Note:
To
execute
above
program
correctly,
supply
valid
integers
in
command
line
arguments.
Right
click
on
Project
->
Select
Properties
->
Click
on
Debug
tab
and
enter
few
values
in
Command
line
arguments
section
seperated
by
spaces.
For
this
example
we
have
used
the
values:
2
3
12
Language Basics
Chapter-3
Fig: 3.2 Switch statement syntax: switch (expr) //expr can only integral type / char / string { case 0: //value of case must be a constant. statements; goto default; // or break can be used. case 1: case 2: statements; break; //break must be preset after every case with statements default: statements; break; //break must be present after default also. } Task: Write a program to print grade of the person based on the marks scored. while..loop statement syntax: while (BooleanExpression) { Statements; } do { Statements } while (BooleanExpression) }
13
Language Basics
Chapter-3
Program to Print the table of any number read from the keyboard. using System; class Program { public static void Main() { int n; Console.Write("Table of: "); n = int.Parse(Console.ReadLine()); string s = ""; for (int i = 1; i <= 10; i++) s += n + "*" + i + "=" + n * i + "\n"; Console.WriteLine(s); } } Code: 3.4 C# Here is the output of executing above code:
Fig: 3.3 for statement syntax: for ( initializer; condition; iterator ) { statements; } Sample program implementing for loops Example 1 using System; class Program { static void Main(string[] args) { for (int i = 0; i < 3; i++)
14
Language Basics
Chapter-3
Fig: 3.4 Sample program implementing for loops Example 2 using System; class Program { static void Main(string[] args) { for (int i = 0; i < 10; i++) { if (i == 7) break; if (i == 3) continue; Console.WriteLine(i); } } } Code: 3.6 C# Here is the output of executing above code:
15
Language Basics
Chapter-3
Fig: 3.5 Program to show the Pyramid of Numbers using System; class Program { static void Main(string[] args) { int k = 0; for (int i = 0; i < 4; i++) { for (int j = 0; j <= i; j++) Console.Write(k++ + "\t"); Console.WriteLine(); } } } Code: 3.7 C# Here is the output of executing above code:
Fig: 3.6
16
Language Basics
Chapter-3
17
Language Basics
Chapter-3
18
Language Basics
Chapter-3
Fig: 3.7 Program: To read a list of numbers separated by space and print the Average of all those numbers. using System; class ProgramForMaxOfAnyNumbers { static void Main(string[] args) { string str = Console.ReadLine(); string[] ar = str.Split(' '); int sum = 0; for (int i = 0; i < ar.Length; i++) { sum += int.Parse(ar[i]); Console.WriteLine(ar[i]); } Console.WriteLine("Average: " + 1.0 * sum / ar.Length); } } Code: 3.10 C#
19
Language Basics
Chapter-3
Fig: 3.8 Program: To read length and data for an array from keyboard print the same. using System; class ProgramForMaxOfAnyNumbers { static void Main() { Console.Write("Enter the array length: "); int n; n = int.Parse(Console.ReadLine()); int[] ar = new int[n]; for (int i = 0; i < n; i++) { Console.Write("Enter the " + i + "th value: "); ar[i] = int.Parse(Console.ReadLine()); } for (int i = 0; i < ar.Length; i++) { Console.Write(ar[i] + " "); } } } Code: 3.11 C#
20
Language Basics
Chapter-3
Fig: 3.9
21
Language Basics
Chapter-3
22
Language Basics
Chapter-3
Fig: 3.10 Params Parameters: 1. Only Parameters which are of type array (of any data type) can be declared as params 2. If parameter is declared as params either a reference to the array can be passed as argument or 0 or more individual values can be passed to it. 3. Only one parameter of a method can be declared as params parameter. 4. It must be last parameter in the list of parameters for a given method. 5. If we have other parameters in the list they must be before the params parameter and they cannot be declared as optional. using System; class Program { public static void Main() { int res = Add(10, 2); int[] mar = { 1, 2, 3, 4 }; res = Add(mar); Console.WriteLine(res.ToString()); res = Add(); res = Add(1, 2, 3, 4, 5); res = Add(1, 2, 3, 4, 5, 6); res = Add(1, 2, 3, 4, 5, 6, 7); Console.WriteLine(res.ToString()); } static int Add(params int[] ar) { int sum = 0; foreach (int n in ar) sum += n; return sum; } } Code: 3.13 C# Here is the output of executing above code:
23
Language Basics
Chapter-3
Fig: 3.11 Pass by value and reference example using System; class Program { public static void Main() { int n1, n2, n3; n1 = n3 = 10; Foo(n1, out n2, ref n3); Console.WriteLine(n1 + " " + n2 + " " + n3); } static void Foo(int a, out int b, ref int c) { a++; b = 20; c++; } } Code: 3.14 C# Here is the output of executing above code:
Fig: 3.13
24
Language Basics
Chapter-3
The argument n2 is passed by reference to b, i.e. both b and n2 reference to same memory and hence change made to b is also reflected in n2. Out parameter must be initialized in the method and are generally used in situations where we want to return more than one value from the method. If a method has return type anything other than void, all code paths in it must return a value. The example below compilation error because if a==0 nothing is mentioned as return value: static int Foo(int a) { if (a != 0) return a; }
Summary
In
this
section
we
have
covered
most
of
the
C#
language
structures
that
includes:
Datatypes
declaration
&
initialization,
conditional
and
looping
structures,
working
with
arrays
&
methods
and
enumerated
datatypes.
25