TrainingMaterials Day2
TrainingMaterials Day2
Object lifetime
Basic c# Syntax
Strongly type -
Case-sensitive
Line ends with semi-colon
using System;
class Hello {
static void Main() {
Console.WriteLine("Hello World");
}
}
Comments
/* */ - multi line
// - single line
/// - XML documentation
Necessity of comments
/*
*
***************************************************************************
**
NAME:TaxDetails.aspx
PURPOSE:Create a page for Tax Details
REVISIONS:
Ver Date Author CR#/Release Description
--------- ------------ --------------- ------------
------------------------------------
1.0 22/01/2013 ABC Created Created
1.1 16/04/2013 ABC Modified Serial No not coming properly
solved the ST issue.
***************************************************************************
************************************************
*/
Data Types
Reference types can be self-describing types, pointer types, or interface types. Variables that are
value types each have their own copy of the data, and therefore operations on one variable do not
affect other variables. Variables that are reference types can refer to the same object; therefore,
operations on one variable can affect the same object referred to by another variable. All types
derive from the System.Object base type.
Integer Type
Decimal type
Boolean Type
Char type
using System;
class StringExample
{
public static int Main()
{
string s1 = a string;
string s2 = s1;
Console.WriteLine(s1 is + s1);
Console.WriteLine(s2 is + s2);
s1 = another string;
Console.WriteLine(s1 is now + s1);
Console.WriteLine(s2 is now + s2);
return 0;
}
}
Varibles
Variables are programming elements that can change during program execution. Theyre
used as storage to hold information at any stage of computation. As a program executes,
certain variables change to support the goals of an algorithm. The syntax of a variable
definition uses the following pattern:
Type Identifier [= Initializer];
Object declaration
Customer cust = new Customer();
Accessibility Levels -
Following are the five levels of access modifiers :-
Private : Only members of class have access.
Protected :-All members in current class and in derived classes variables.
Friend (internal in C#) :- Only members in current project have elements.
Protected friend (protected internal in C#) :- All members in current and all members in
derived class can access the variables.
Public :- All members have access in all classes and projects.
Operators
Unary Operators
Binary Operators
Ternary Operator
Other Operator
Unary Operator
Unary operators affect a single expression.
Plus,
Minus,
Increment (post & pre)
Decrement (post & pre)
Logical Compliment (A logical complement operator (!) inverts the result of a Boolean)
BitwiseCompliment ((~) inverts the binary representation of an expression)
byte bitComp = 15; // bitComp = 15 = 00001111b
byte byteResult = (byte) ~bitComp; // bresult = 240 = 11110000b
Binary Operators
Binary operators work with two operands. For example, a common binary expression
would be a + bthe addition operator (+) surrounded by two operands. The binary operators
are further subdivided into
arithmetic,
relational,
logical, and
assignment operators.
Arithmetic
multiplication *
Division /
Modulus %
Addition +
Substraction
Left Shift
Right Shift
Relational
Equal ==
No Equal !=
Less than <
Greater than >
Less than or equal <=
Greater than or equal >=
Logical
Logical operators perform Boolean logic on two expressions. There are three types of
logical operators in C#:
bitwise,
Boolean, and
conditional.
The bitwise logical operators perform Boolean logic on corresponding bits of two integral
expressions. Valid integral types are the signed and unsigned int and long types. C#
promotes byte to int, which is why the example in the prevous section worked. The
bitwise logical operators return a compatible integral result with each bit conforming to
the Boolean evaluation.
Boolean logical operators perform Boolean logic upon two Boolean expressions. The expression
on the left is evaluated, and then the expression on the right is evaluated. Finally, the
two expressions are evaluated together in the context of the Boolean logical operator
between them. They return a bool result corresponding to the type of operator used.
The conditional logical operators operate much the same way as the Boolean logical operators
with one exception: When the first expression is evaluated and found to satisfy the
results of the entire expression, the second expression is not evaluated. This is efficient
because it doesnt make sense to continue evaluating an expression when the result is
already known.
The bitwise OR operator (|) compares corresponding bits of two integrals and
returns a result with corresponding bits set to 1 if either of the integrals have 1 bits in that
position. When both integrals have a 0 in corresponding positions, the result is 0 in that
position.
Boolean AND
The Boolean AND operator (&) evaluates two Boolean expressions and returns true when
both expressions evaluate to true. Otherwise, the result is false. The result of each
expression evaluated must return a bool.
Boolean OR
The Boolean OR operator (|) evaluates the results of two Boolean expressions
and returns true if either of the expressions returns true. When both expressions are
false, the result of the Boolean inclusive OR evaluation is false. Both expressions evaluated
must return a bool type value.
Notice that because mileage > 3000 is true, months > 3 will never be evaluated.
Assignment Operator
= += -= *= /= %= <<= >>= &= ^= |=
Ternary Operator
The ternary operator contains three expressions, thus the name ternary. The first expression
must be a Boolean expression. When the first expression evaluates to true, the value
of the second expression is returned. When the first expression evaluates to false, the
value of the third expression is returned. This is a concise and short method of making a
decision and returning a choice based on the result of the decision. The ternary operator is
often called the conditional operator. Heres an example:
Other Operators
C# has some operators that cant be categorized as easily as the other types. These include
the
is,
as,
sizeof(),
typeof(),
checked(), and
unchecked() operators.
Conditional Statements
If
if (Boolean expression)
[{]
true condition statement(s)
[}]
if (args.Length == 0)
{
Console.WriteLine(Invalid # of command line args);
}
If-then-else
if (args.Length == 0)
{
Console.WriteLine(Invalid # of command line args);
}
else
{
Console.WriteLine(You entered: {0}?, args[0]);
}
If-else-elseif
if (args.Length == 0)
{
Console.WriteLine(Invalid # of command line args);
}
else if (args.Length == 1)
{
Console.WriteLine(You entered: {0}?, args[0]);
}
else
{
Console.WriteLine(Too many arguments!\a);
}
Switch
switch (choice)
{
case A:
Console.WriteLine(Add Site);
break;
case S:
Console.WriteLine(Sort List);
break;
case R:
Console.WriteLine(Show Report);
break;
case Q:
Console.WriteLine(GoodBye);
break;
default:
Console.WriteLine(Huh??);
break;
}
Looping Structures
While
Do
For
Foreach
foreach
foreach (type identifier in collection)
[{]
statement(s)
[}]
Statements goto. Break, continue, return
ASSIGNMENT
Functions
Overview, difference with method
Exception Handling
Try/catch/finally
using System;
public class Exceptions
{
public static int Main(string[] args)
{
byte[] myStream = new byte[3];
try
{
for (byte b=0; b < 10; b++)
{
Console.WriteLine(Byte {0}: {1}, b+1, b);
myStream[b] = b;
}
}
catch (Exception e)
{
Console.WriteLine({0}, e.Message);
}
return 0;
}
}
Output:
Byte 1: 0
Byte 2: 1
Byte 3: 2
Byte 4: 3
Index was outside the bounds of the array.
Multiple Catch
using System;
using System.IO;
public class Exceptions3
{
public static int Main(string[] args)
{
int mySize = 3;
byte[] myStream = new byte[mySize];
int iterations = 5;
StreamWriter sw = new StreamWriter(exceptions.txt);
try
{
for (byte b=0; b < iterations; b++)
{
sw.WriteLine(Byte {0}: {1}, b+1, b);
myStream[b] = b;
}
}
catch (IndexOutOfRangeException iore)
{
Console.WriteLine(
Index Out of Range Exception: {0},
iore.Message);
}
catch (Exception e)
{
Console.WriteLine(Exception: {0}, e.Message);
}
finally
{
sw.WriteLine(Close);
sw.Close();
}
return 0;
}
}
using System;
using System.IO;
public class Exceptions4
{
public static int Main(string[] args)
{
Exceptions4 myExceptionMaker = new Exceptions4();
try
{
myExceptionMaker.GenerateException();
}
catch (Exception e)
{
Console.WriteLine(\nNow processing Main() Exception:);
while (e != null)
{
11
Console.WriteLine(\tInner: {0}, e.Message);
e = e.InnerException;
}
}
finally
{
Console.WriteLine(Finally from Main());
}
return 0;
}
void GenerateException()
{
int mySize = 3;
byte[] myStream = new byte[mySize];
int iterations = 5;
StreamWriter sw = new StreamWriter(exceptions.txt);
try
{
for (byte b=0; b < iterations; b++)
{
sw.WriteLine(Byte {0}: {1}, b+1, b);
myStream[b] = b;
}
}
catch (IndexOutOfRangeException iore)
{
Console.WriteLine(
\nIndex Out of Range Exception from GenerateException: {0},iore.Message);
throw new Exception(
Thrown from GenerateException.,iore);
}
catch (Exception e)
{
Console.WriteLine(
\nException from GenerateException: {0}, e.Message);
}
finally
{
Console.WriteLine(Finally from GenerateException.);
sw.WriteLine(Close);
sw.Close();
}
}
}
Output
Heres the codes output:
Index Out of Range Exception from GenerateException: An exception of type System
.IndexOutOfRangeException was thrown.
Finally from GenerateException.
Arrays
Single-dimension arrays let you store and manipulate a list of objects. Every element is of
the same (or derived if applicable) type. Heres the basic syntax:
e.g.
// uninitialized declaration
byte[] inputBuffer = new byte[2048];
Its common to use loops to access each element of an array. Heres an example using a
for loop:
for (int i = 0; i < countStrings.Length; i++)
{
Console.WriteLine(countStrings[i]);
}
Multi-dimension array
A multidimension array differs from a single-dimension array in that it contains two or
more dimensions.
Jagged Array
The jagged array has characteristics of a single dimension array in that it is an
array of arrays.
An array list is very similar to an array, except that it has the ability to grow. It is represented
by the class
System.Collections.ArrayList.
If you try to add more objects to the ArrayList than permitted, then it will automatically
increase its capacity by allocating a new area of memory big enough to hold twice as many
elements as the current capacity, and relocate the objects to thisnew location.
Hashtable provides way to access elements using a KEY, thus removing the index problem,
which may not be known always.
using System.Collections;
if (myHash.ContainsKey(strUserID.ToLower()))
{
string values = Convert.ToString(myHash[strUserID.ToLower()]);
myHash.Remove(strUserID.ToLower());
myHash.Add(strUserID.ToLower(), value);
}
Generic Collections
Generic types allow you to parameterize your code and then use that code by filling in a
type parameter with whatever object type you want that generic type to work on.
A generic List
Generic List will generate error when Employee object is getting added
Boxing permits any value type to be implicitly converted to type object or to any interface type
implemented by value type.
Boxing is a process in which object instances are created and copy values in to that instance.
Unboxing is vice versa of boxing operation where the value is copied from the instance in to
appropriate storage location.
Below is sample code of boxing and unboxing where integer data type is converted in to object
and then vice versa.
Dim x As Integer
Dim y As Object
x = 10
boxing process
y=x
unboxing process x = y
Using generics, you can make assignments in a strongly typed manner.
Class, Object
Base Class, Derived Class, Sealed Class, Abstract Class, Nested Class, Partial Class, Static
Class
Base keyword
public class A
{
public A( int var )
{
this.x = var;
}
public virtual void DoSomething()
{
System.Console.WriteLine( "A.DoSomething" );
}
private int x;
}
public class B : A
{
public B() : base( 123 )
{
}
public override void DoSomething()
{
System.Console.WriteLine( "B.DoSomething" );
base.DoSomething();
}
}
public class EntryPoint
{
static void Main()
{
B b = new B();
b.DoSomething();
}
}
Accessibility Levels -
Following are the five levels of access modifiers :-
Private : Only members of class have access.
Protected :-All members in current class and in derived classes variables.
Friend (internal in C#) :- Only members in current project have elements.
Protected friend (protected internal in C#) :- All members in current and all members in
derived class can access the variables.
Public :- All members have access in all classes and projects.
Polymorphism
public class GeometricShape
{
public virtual void Draw()
{
// Do some default drawing stuff.
}
}
public class Rectangle : GeometricShape
{
public override void Draw()
{
// Draw a rectangle
}
}
public class Circle : GeometricShape
{
public override void Draw()
{
// Draw a circle
}
}
Sealed Class
C# offers the sealed keyword for the occasions when you never want a client to derive
from a
class. When applied to the entire class, the sealed keyword indicates that this class is a
leaf class.
Abstract Class
You cannot create an object of abstract class
Abstract class is designed to act as a base class (to be inherited by other classes).
Abstract class is a design concept in program development and provides a base
upon which other classes are built.
Abstract classes can have implementation or pure abstract methods which should
be implemented in the child class.
They establish structure and meaning to code. This is possible because abstract classes have
information and behavior common to all derived classes in a framework. All common
functionalities are put in Abstract Class
Nested class
Nested classes are classes within classes.
In sample below ClsNested class has a ChildNested class nested inside it.
PublicClassClsNested
PublicClassChildNested
PublicSubShowMessage()
MessageBox.Show(Hithisisnestedclass)
EndSub
EndClass
EndClass
This is the way we can instantiate the nested class and make the method call.
DimpobjChildNestedAsNewClsNested.ChildNested()
pobjChildNested.ShowMessage()
Static Classes
Normal classes can have instance and static members, but sometimes we need to create static
classes with only static members.
All members of the static class must be static.
They are used when a class provides functionality which is not specific to any instance. In
short if you want an object to be shared between multiple instances you will use a
static/Shared class.
Following are features of Static/Shared classes:-
They cannot be instantiated. By default an object is created on the first method call to
that object.
Static/Shared classes cannot be inherited.
Static/Shared classes can have only static members.
Static/Shared classes can have only static constructor.
Partial Classes
The syntax identifying a partial type includes a class (or struct) definition with the partial
modifier. At compile time, C# identifies all classes defined with the same name that have
partial modifiers and compiles them into a single type. The following code shows the
syntax of partial types:
using System;
partial class Program
{
static void Main()
{
m_someVar = 5;
}
}
// Located in a different file
using System;
partial class Program
{
private static int m_someVar;
}
ASSIGNMENT
Create a Static Class and use its method and properties
Create a base Class and create a derived class with override methods
Constructors
Constructors are called when a class is first loaded by the CLR or an object is
created. There are two
types of constructors: static constructors and instance constructors. A class can
have only one static
constructor, and it can have no parameters. The name of the static constructor
must match the
name of the class it belongs to. As with any other class member, you can attach
metadata attributes
to the static constructor.
Instance constructors, on the other hand, are called when an instance of a class
is creat
Property Procedures
Enumerations
An enum type is a list of strongly typed constant values. Just like a class or struct is used
to create custom reference type and value type objects, an enum allows you to create a
custom value type. They are meant to be reused across a program, so you typically declare
enum types at the namespace level.
enum Months { Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec }
Value types directly contain their data which are either allocated on the
stack or allocated in-line in a structure. Reference types store a reference to
the value's memory address, and are allocated on the heap. Reference types
can be self-describing types, pointer types, or interface types.
Variables that are value types each have their own copy of the data, and
therefore operations on one variable do not affect other variables. Variables
that are reference types can refer to the same object; therefore, operations
on one variable can affect the same object referred to by another variable.
All types derive from the System.Object base type.
Structures
Following are the similarities between classes and structures :-
Both can have constructors, methods, properties, fields,
constants, enumerations, events, and event handlers.
Structures and classes can implement interface.
Both of them can have constructors with and without parameter.
Both can have delegates and events.
Namespaces
In Object Oriented world many times its possible that programmers will use the same
class name.By qualifying NameSpace with classname this collision can be avoided.