Sie sind auf Seite 1von 85

BY: Sharad Pyakurel

C#
57

BY: Sharad Pyakurel

C# GENERAL TOPICES
Introduction Of .NET Framework Basic Features Of .NET Languages Assemblies Structure of C# Program C# Console C# Variables Keywords Control (if, switch) statements Looping Ststements (for, foreach, while, do-while) Statements Goto, break, return statements Namespaces

C# Objects And Types Concept of object and object oriented programming Classes and structs C# Methods Properties Constructors, constructor overloading Destructors Partial classes Static classes, properties and methods Encapsulation

Inheritance Concept of Inheritance Implementation of Inheritance Virtual Methods Abstract classes and Functions Parameterised Constructors Methods overloading

C# Interface Defination and declaration of interface Derived interfaces

57

BY: Sharad Pyakurel

Implementation of interfaces IComparable, IEnumerable, IDisposable, ICollection

Delegate And Events Introduction Of Delegate Declaration of delegate Delegate implementation

Strings And Regular Expressions String Operations And Formetting Implementation of StringBuilder Implementation of Regular Expression

Collections Introduction Of Collection ArrayList Stack Queue Dictionaries and HashTable

Generics In C#(Concept and implementation) Threading (Concept And Implementation) Localization and Globalization Deployment Data Access ADO.NET Introduction DataSet, DataTable Database Specific Classes(SqlConnection, SqlCommand, SqlTransaction etc) Database Connection Executing Commands (ExecuteNonQuery(), ExecuteReader(), ExecuteScalar()) Stored Procedure Concept and Implementation

Windows Forms And Controls Form Inheritance Using Windows Form Controls

57

BY: Sharad Pyakurel

Graphics (GDI+) IO LINQ Introduction Of LINQ Implementation of LINQ Common Dialogs (Open, Save, Color, font , print preview, print dialogs) Streams File Operations (Creating,deleting , Reading and Writing) in file

Crystal Report Reporting Concept in CrystalReport Designing And Formatting Complex Reports in Crystal Report Syntax of writing formula in Crystal Report Using Typed DataSet as DataSource In Crystal Report SubReports In Crystal Report

57

BY: Sharad Pyakurel

Introduction Of .NET Framework


Basic Features of .NET Languages:
C# (pronounced See Sharp) is a simple, modern, object-oriented, and type-safe programming language. C# has its roots in the C family of languages and will be immediately familiar to C, C++, and Java programmers. Several C# features aid in the construction of robust and durable applications: Garbage collection automatically reclaims memory occupied by unused objects; exception handling provides a structured and extensible approach to error detection and recovery; and the type-safe design of the language makes it impossible to read from uninitialized variables, to index arrays beyond their bounds, or to perform unchecked type casts. Some Basic Features of .NET Language are listed as:.Net Programs are compiled not interpreted. Multilanguage: .Net Application can be created using different languages like C#, J#, Visual Basic, because codes are compiled in to IL. Object Oriented Type Safe

Process of .NET Language Compilation:


There are two stages in .Net code compilation. In First stage the .net Code (Say C#) code written is compiled into an intermediate language called Microsoft Intermediate language (MSIL) code. The second stage of compilation happens just before the actual execution. Here IL Code is compiled into Low Level native machine code. This stage is known as Just in Time (JIT) compilation. Code in C# C# Compiler IL (Intermediate Language Code) Just In Time (JIT) Compiler Native Machine Code Execute

Assemblies:

57

BY: Sharad Pyakurel

An Assembly is the logical unit that contains compiled code targeted at the .NET Framework. Assemblies contain metadata that describes the types and methods defined in the corresponding code. Assemblies contain executable code in the form of Intermediate Language (IL) instructions, and symbolic information in the form of metadata. Before it is executed, the IL code in an assembly is automatically converted to processor-specific code by the Just-In-Time (JIT) compiler of .NET Common Language Runtime.

Structure of C# Program:
The key organizational concepts in C# are programs, namespaces, types, members, and assemblies. C# programs consist of one or more source files. Programs declare types, which contain members and can be organized into namespaces. Classes and interfaces are examples of types. Fields, methods, properties, and events are examples of members. When C# programs are compiled, they are physically packaged into assemblies. Assemblies typically have the file extension .exe or .dll, depending on whether they implement applications or libraries. Using system; Namespace studeinfo { Class myClass { Static void main() { Console.WriteLine(Hello How are you); Console.ReadLine(); Return; } } } For Compiling in Command Line CSC FileName.cs For Executing FileName.exe

Keywords:
A keyword is an identifier-like sequence of characters that is reserved, and cannot be used as an identifier except when prefaced by the @ character.

57

BY: Sharad Pyakurel

keyword:
abstract byte class delegate event fixed if internal new override readonly short struct try unsafe volatile

one
as base bool break case catch char checked const continue decimal default do double else enum explicit extern false finally float for foreach goto implicit in int interface is lock long namespace null object operator out params private protected public ref return sbyte sealed sizeof stackalloc static string switch this throw true typeof uint ulong unchecked ushort using virtual void while

of

C# Types and Variables:


There are two kinds of types in C#: value types and reference types. Variables of value types directly contain their data whereas variables of reference types store references to their data, the latter being known as objects. With reference types, it is possible for two variables to reference the same object and thus possible for operations on one variable to affect the object referenced by the other variable. With value types, the variables each have their own copy of the data, and it is not possible for operations on one to affect the other (except in the case of ref and out parameter variables). C#s value types are further divided into simple types, enum types, struct types, and nullable types, and C#s reference types are further divided into class types, interface types, array types, and delegate types. The following table provides an overview of C#s type system.

57

BY: Sharad Pyakurel

Category Value types Simple types

Description Signed integral: sbyte, short, int, long Unsigned integral: byte, ushort, uint, ulong Unicode characters: char IEEE floating point: float, double High-precision decimal: decimal Boolean: bool Enum types Struct types Nullable types User-defined types of the form enum E {...} User-defined types of the form struct S {...} Extensions of all other value types with a null value Ultimate base class of all other types: object Unicode strings: string User-defined types of the form class C {...} Interface types Array types Delegate types User-defined types of the form interface I {...} Single- and multi-dimensional, for example, int[] and int[,] User-defined types of the form e.g. delegate int D(...)

Reference types

Class types

The eight integral types provide support for 8-bit, 16-bit, 32-bit, and 64-bit values in signed or unsigned form. The two floating point types, float and double, are represented using the 32-bit single-precision and 64-bit double-precision IEEE 754 formats. The decimal type is a 128-bit data type suitable for financial and monetary calculations. C#s bool type is used to represent boolean valuesvalues that are either true or false. Character and string processing in C# uses Unicode encoding. The char type represents a UTF-16 code unit, and the string type represents a sequence of UTF-16 code units. The following table summarizes C#s numeric types.

57

BY: Sharad Pyakurel

Category Signed integral

Bit s 8 16 32 64

Type
sbyte short int long

Range/Precision 128...127 32,768...32,767 2,147,483,648...2,147,483,647 9,223,372,036,854,775,808...9,223,372,036,854,775,80 7 0...255 0...65,535 0...4,294,967,295 0...18,446,744,073,709,551,615 1.5 1045 to 3.4 1038, 7-digit precision 5.0 10324 to 1.7 10308, 15-digit precision 1.0 1028 to 7.9 1028, 28-digit precision

Unsigned integral

8 16 32 64

byte ushort uint ulong float double decimal

Floating point Decimal

32 64 128

C# programs use type declarations to create new types. A type declaration specifies the name and the members of the new type. Five of C#s categories of types are user-definable: class types, struct types, interface types, enum types, and delegate types. A class type defines a data structure that contains data members (fields) and function members (methods, properties, and others). Class types support single inheritance and polymorphism, mechanisms whereby derived classes can extend and specialize base classes. A struct type is similar to a class type in that it represents a structure with data members and function members. However, unlike classes, structs are value types and do not require heap allocation. Struct types do not support user-specified inheritance, and all struct types implicitly inherit from type object. An interface type defines a contract as a named set of public function members. A class or struct that implements an interface must provide implementations of the interfaces function members. An interface may inherit from multiple base interfaces, and a class or struct may implement multiple interfaces. A delegate type represents references to methods with a particular parameter list and return type. Delegates make it possible to treat methods as entities that can be assigned to variables and passed as parameters. Delegates are similar to the concept of function pointers found in some other languages, but unlike function pointers, delegates are object-oriented and type-safe. Class, struct, interface and delegate types all support generics, whereby they can be parameterized with other types. An enum type is a distinct type with named constants. Every enum type has an underlying type, which must be one of the eight integral types. The set of values of an enum type is the same as the set of values of the underlying type. C# supports single- and multi-dimensional arrays of any type. Unlike the types listed above, array types do not have to be declared before they can be used. Instead, array types are constructed by following a type name with square brackets. For example, int[] is a single-dimensional array of int, int[,] is a two-dimensional array of int, and int[][] is a single-dimensional array of single-dimensional arrays of int. Nullable types also do not have to be declared before they can be used. For each non-nullable value type T there is a corresponding nullable type T?, which can hold an additional value null. For instance, int? is a type that can hold any 32 bit integer or the value null.

57

BY: Sharad Pyakurel

- Variables represent storage locations, and every variable has a type that determines what values can be stored in the variable. There are several kinds of variables in C#, including fields, array elements, local variables, and parameters. Type of Variable Possible Contents

Non-nullable value A value of that exact type type Nullable value type
object

A null value or a value of that exact type A null reference, a reference to an object of any reference type, or a reference to a boxed value of any value type A null reference, a reference to an instance of that class type, or a reference to an instance of a class derived from that class type A null reference, a reference to an instance of a class type that implements that interface type, or a reference to a boxed value of a value type that implements that interface type A null reference, a reference to an instance of that array type, or a reference to an instance of a compatible array type A null reference or a reference to an instance of that delegate type

Class type Interface type

Array type Delegate type

C# Expressions:
Expressions are constructed from operands and operators. The operators of an expression indicate which operations to apply to the operands. Examples of operators include +, -, *, /, and new. Examples of operands include literals, fields, local variables, and expressions. When an expression contains multiple operators, the precedence of the operators controls the order in which the individual operators are evaluated. For example, the expression x + y * z is evaluated as x + (y * z) because the * operator has higher precedence than the + operator. Most operators can be overloaded. Operator overloading permits user-defined operator implementations to be specified for operations where one or both of the operands are of a user-defined class or struct type. The following table summarizes C#s operators, listing the operator categories in order of precedence from highest to lowest. Operators in the same category have equal precedence.

57

BY: Sharad Pyakurel

Category Primary

Expression
x.m x(...) x[...] x++ x-new T(...) new T(...){...} new {...} new T[...] typeof(T) checked(x) unchecked(x) default(T) delegate {...}

Description Member access Method and delegate invocation Array and indexer access Post-increment Post-decrement Object and delegate creation Object creation with initializer Anonymous object initializer Array creation Obtain System.Type object for T Evaluate expression in checked context Evaluate expression in unchecked context Obtain default value of type T Anonymous function (anonymous method) Identity Negation Logical negation Bitwise negation Pre-increment Pre-decrement Explicitly convert x to type T Multiplication Division Remainder Addition, string combination concatenation, delegate

Unary

+x -x !x ~x ++x --x (T)x

Multiplicative

x*y x/y x%y

Additive

x+y xy

Subtraction, delegate removal

57

BY: Sharad Pyakurel

Shift

x << y x >> y

Shift left Shift right Less than Greater than Less than or equal Greater than or equal Return true if x is a T, false otherwise Return x typed as T, or null if x is not a T Equal Not equal Integer bitwise AND, boolean logical AND Integer bitwise XOR, boolean logical XOR Integer bitwise OR, boolean logical OR Evaluates y only if x is true Evaluates y only if x is false Evaluates to y if x is null, to x otherwise Evaluates y if x is true, z if x is false Assignment Compound assignment; supported operators are
*= /= %= += -= <<= >>= &= ^= |=

Relational and x < y type testing


x>y x <= y x >= y x is T x as T

Equality Logical AND Logical XOR Logical OR Conditional AND Conditional OR Null coalescing Conditional Assignment anonymous function

x == y x != y x&y x^y x|y x && y x || y X ?? y x?y:z

or x = y
x op= y (T x) => y

Anonymous function (lambda expression)

Statements In C#:
The actions of a program are expressed using statements. C# supports several different kinds of statements, a number of which are defined in terms of embedded statements. A block permits multiple statements to be written in contexts where a single statement is allowed. A block consists of a list of statements written between the delimiters { and }. Declaration statements are used to declare local variables and constants. Expression statements are used to evaluate expressions. Expressions that can be used as statements include method invocations, object allocations using the new operator, assignments using = and the compound assignment operators, and increment and decrement operations using the ++ and -- operators. Selection statements are used to select one of a number of possible statements for execution based on the value of some expression. In this group are the if and switch statements. Iteration statements are used to repeatedly execute an embedded statement. In this group are the while, do, for, and foreach statements. Jump statements are used to transfer control. In this group are the break, continue, goto, throw, return, and yield statements. The try...catch statement is used to catch exceptions that occur during execution of a block, and the try...finally statement is used to specify finalization code that is always executed, whether an exception occurred or not. The checked and unchecked statements are used to control the overflow checking context for integral-type arithmetic operations and conversions.

57

BY: Sharad Pyakurel

The lock statement is used to obtain the mutual-exclusion lock for a given object, execute a statement, and then release the lock. The using statement is used to obtain a resource, execute a statement, and then dispose of that resource. The following table lists C#s statements and provides an example for each one. Statement
Local variable declaration

Example
static void Main() { int a; int b = 2, c = 3; a = 1; Console.WriteLine(a + b + c); } static void Main() { const float pi = 3.1415927f; const int r = 25; Console.WriteLine(pi * r * r); } static void Main() { int i; i = 123; Console.WriteLine(i); i++; Console.WriteLine(i); }

Local constant declaration

Expression statement

// Expression statement // Expression statement // Expression statement // Expression statement

if statement

static void Main(string[] args) { if (args.Length == 0) { Console.WriteLine("No arguments"); } else { Console.WriteLine("One or more arguments"); } } static void Main(string[] args) { int n = args.Length; switch (n) { case 0: Console.WriteLine("No arguments"); break; case 1: Console.WriteLine("One argument"); break; default: Console.WriteLine("{0} arguments", n); break; } } } static void Main(string[] args) { int i = 0; while (i < args.Length) { Console.WriteLine(args[i]); i++; } } static void Main() { string s;

switch statement

while statement

do statement

57

BY: Sharad Pyakurel do { s = Console.ReadLine(); if (s != null) Console.WriteLine(s); } while (s != null); } for statement static void Main(string[] args) { for (int i = 0; i < args.Length; i++) { Console.WriteLine(args[i]); } } static void Main(string[] args) { foreach (string s in args) { Console.WriteLine(s); } } static void Main() { while (true) { string s = Console.ReadLine(); if (s == null) break; Console.WriteLine(s); } } static void Main(string[] args) { for (int i = 0; i < args.Length; i++) { if (args[i].StartsWith("/")) continue; Console.WriteLine(args[i]); } }

foreach statement

break statement

continue statement

goto statement

static void Main(string[] args) { int i = 0; goto check; loop: Console.WriteLine(args[i++]); check: if (i < args.Length) goto loop; } static int Add(int a, int b) { return a + b; } static void Main() { Console.WriteLine(Add(1, 2)); return; }

return statement

yield statement

static IEnumerable<int> Range(int from, int to) { for (int i = from; i < to; i++) { yield return i; } yield break; } static void Main() { foreach (int x in Range(-10,10)) { Console.WriteLine(x); } }

throw and try

static double Divide(double x, double y) { if (y == 0) throw new DivideByZeroException();

57

BY: Sharad Pyakurel statements } static void Main(string[] args) { try { if (args.Length != 2) { throw new Exception("Two numbers required"); } double x = double.Parse(args[0]); double y = double.Parse(args[1]); Console.WriteLine(Divide(x, y)); } catch (Exception e) { Console.WriteLine(e.Message); } finally { Console.WriteLine(Good bye!); } } checked and unchecked statements static void Main() { int i = int.MaxValue; checked { Console.WriteLine(i + 1); } unchecked { Console.WriteLine(i + 1); } } return x / y;

// Exception // Overflow

lock statement

class Account { decimal balance; public void Withdraw(decimal amount) { lock (this) { if (amount > balance) { throw new Exception("Insufficient funds"); } balance -= amount; } } }

using statement

static void Main() { using (TextWriter w = File.CreateText("test.txt")) { w.WriteLine("Line one"); w.WriteLine("Line two"); w.WriteLine("Line three"); } }

Namespace:
C# programs are organized using namespaces. Namespaces are used both as an internal organization system for a program, and as an external organization systema way of presenting program elements that are exposed to other programs. Namespace provides a way of organizing related classes and other types. Namespace is a logical grouping; different namespaces can be accepted in the same assembly. A namespace-declaration consists of the keyword namespace, followed by a namespace name and body, optionally followed by a semicolon.

57

BY: Sharad Pyakurel

namespace-declaration: namespace qualified-identifier namespace-body ;opt qualified-identifier: identifier qualified-identifier . identifier namespace-body: { extern-alias-directivesopt using-directivesopt namespace-member-declarationsopt } For e.g. Namespace n1 { Namespace n2 { Class clsExample { //Code For Class } } } This can also be written as: Namespace n1.n2 { Class clsExample { //Code For Class } }

57

BY: Sharad Pyakurel

Classes and objects


Classes are the most fundamental of C#s types. A class is a data structure that combines state (fields) and actions (methods and other function members) in a single unit. A class provides a definition for dynamically created instances of the class, also known as objects. Classes support inheritance and polymorphism, mechanisms whereby derived classes can extend and specialize base classes. New classes are created using class declarations. A class declaration starts with a header that specifies the attributes and modifiers of the class, the name of the class, the base class (if given), and the interfaces implemented by the class. The header is followed by the class body, which consists of a list of member declarations written between the delimiters { and }. The following is a declaration of a simple class named Point:
public class Point { public int x, y; public Point(int x, int y) { this.x = x; this.y = y; } }

Instances of classes are created using the new operator, which allocates memory for a new instance, invokes a constructor to initialize the instance, and returns a reference to the instance. The following statements create two Point objects and store references to those objects in two variables:
Point p1 = new Point(0, 0); Point p2 = new Point(10, 20);

The memory occupied by an object is automatically reclaimed when the object is no longer in use. It is neither necessary nor possible to explicitly deallocate objects in C#.

Class Members:
The members of a class are either static members or instance members. Static members belong to classes, and instance members belong to objects (instances of classes). The following table provides an overview of the kinds of members a class can contain. Member Constants Fields Methods Properties Indexers Events Operators Constructors Destructors Types Description Constant values associated with the class Variables of the class Computations and actions that can be performed by the class Actions associated with reading and writing named properties of the class Actions associated with indexing instances of the class like an array Notifications that can be generated by the class Conversions and expression operators supported by the class Actions required to initialize instances of the class or the class itself Actions to perform before instances of the class are permanently discarded Nested types declared by the class

57

BY: Sharad Pyakurel

Accessibility Of Class:
Each member of a class has an associated accessibility, which controls the regions of program text that are able to access the member. There are five possible forms of accessibility. These are summarized in the following table. Accessibility
public protected internal protected internal private

Meaning Access not limited Access limited to this class or classes derived from this class Access limited to this program Access limited to this program or classes derived from this class Access limited to this class

Type parameters in Class:


A class definition may specify a set of type parameters by following the class name with angle brackets enclosing a list of type parameter names. The type parameters can the be used in the body of the class declarations to define the members of the class. In the following example, the type parameters of Pair are TFirst and TSecond:
public class Pair<TFirst,TSecond> { public TFirst First; public TSecond Second; }

A class type that is declared to take type parameters is called a generic class type. Struct, interface and delegate types can also be generic. When the generic class is used, type arguments must be provided for each of the type parameters:
Pair<int,string> pair = new Pair<int,string> { First = 1, Second = two }; int i = pair.First; // TFirst is int string s = pair.Second; // TSecond is string

A generic type with type arguments provided, like Pair<int,string> above, is called a constructed type.

Partial types:
A type declaration can be split across multiple partial type declarations. The type declaration is constructed from its parts by following the rules in this section, whereupon it is treated as a single declaration during the remainder of the compile-time and run-time processing of the program. A class-declaration, struct-declaration or interface-declaration represents a partial type declaration if it includes a partial modifier. partial is not a keyword, and only acts as a modifier if it appears immediately before one of the keywords class, struct or interface in a type declaration, or before the type void in a method declaration. In other contexts it can be used as a normal identifier. Each part of a partial type declaration must include a partial modifier. It must have the same name and be declared in the same namespace or type declaration as the other parts. The partial modifier indicates that additional parts of the type declaration may exist elsewhere, but the existence of such additional parts is not a requirement; it is valid for a type with a single declaration to include the partial modifier. All parts of a partial type must be compiled together such that the parts can be merged at compile-time into a single type declaration. Partial types specifically do not allow already compiled types to be extended. Nested types may be declared in multiple parts by using the partial modifier. Typically, the containing type is declared using partial as well, and each part of the nested type is declared in a different part of the containing type.

57

BY: Sharad Pyakurel

The partial modifier is not permitted on delegate or enum declarations. Consider the following partial class declaration:
partial class Customer { string name; public string Name { get { return name; } set { OnNameChanging(value); name = value; OnNameChanged(); } } partial void OnNameChanging(string newName); partial void OnNameChanged(); }

If this class is compiled without any other parts, the defining partial method declarations and their invocations will be removed, and the resulting combined class declaration will be equivalent to the following:
class Customer { string name; public string Name { get { return name; } set { name = value; } } } Assume that another part is given, however, which provides implementing declarations of the partial methods: partial class Customer { partial void OnNameChanging(string newName) { Console.WriteLine(Changing + name + to + newName); } partial void OnNameChanged() { Console.WriteLine(Changed to + name); } } Then the resulting combined class declaration will be equivalent to the following: class Customer { string name; public string Name { get { return name; } set { OnNameChanging(value); name = value; OnNameChanged(); } }

57

BY: Sharad Pyakurel void OnNameChanging(string newName) { Console.WriteLine(Changing + name + to + newName); } void OnNameChanged() { Console.WriteLine(Changed to + name); } }

Fields:
A field is a variable that is associated with a class or with an instance of a class. A field declared with the static modifier defines a static field. A static field identifies exactly one storage location. No matter how many instances of a class are created, there is only ever one copy of a static field. A field declared without the static modifier defines an instance field. Every instance of a class contains a separate copy of all the instance fields of that class. In the following example, each instance of the Color class has a separate copy of the r, g, and b instance fields, but there is only one copy of the Black, White, Red, Green, and Blue static fields:
public class Color { public static readonly Color Black = new Color(0, 0, 0); public static readonly Color White = new Color(255, 255, 255); public static readonly Color Red = new Color(255, 0, 0); public static readonly Color Green = new Color(0, 255, 0); public static readonly Color Blue = new Color(0, 0, 255); private byte r, g, b; public Color(byte r, byte g, byte b) { this.r = r; this.g = g; this.b = b; } }

As shown in the previous example, read-only fields may be declared with a readonly modifier. Assignment to a readonly field can only occur as part of the fields declaration or in a constructor in the same class.

Methods:
A method is a member that implements a computation or action that can be performed by an object or class. Static methods are accessed through the class. Instance methods are accessed through instances of the class. Methods have a (possibly empty) list of parameters, which represent values or variable references passed to the method, and a return type, which specifies the type of the value computed and returned by the method. A methods return type is void if it does not return a value. Like types, methods may also have a set of type parameters, for which type arguments must be specified when the method is called. Unlike types, the type arguments can often be inferred from the arguments of a method call and need not be explicitly given. The signature of a method must be unique in the class in which the method is declared. The signature of a method consists of the name of the method, the number of type parameters and the number, modifiers, and types of its parameters. The signature of a method does not include the return type. Eg:
public class CalculationClass

57

BY: Sharad Pyakurel { private int Add(int num1, int num2) { return num1 + num2; } private decimal divide(decimal first, decimal second) { return first / second; } private string GetMessage() { return "Hello How are you"; } }

Parameters:
Parameters are used to pass values or variable references to methods. The parameters of a method get their actual values from the arguments that are specified when the method is invoked. There are four kinds of parameters: value parameters, reference parameters, output parameters, and parameter arrays. A value parameter is used for input parameter passing. A value parameter corresponds to a local variable that gets its initial value from the argument that was passed for the parameter. Modifications to a value parameter do not affect the argument that was passed for the parameter. Value parameters can be optional, by specifying a default value so that corresponding arguments can be omitted. A reference parameter is used for both input and output parameter passing. The argument passed for a reference parameter must be a variable, and during execution of the method, the reference parameter represents the same storage location as the argument variable. A reference parameter is declared with the ref modifier. The following example shows the use of ref parameters.
using System; class Test { static void Swap(ref int x, ref int y) { int temp = x; x = y; y = temp; } static void Main() { int i = 1, j = 2; Swap(ref i, ref j); Console.WriteLine("{0} {1}", i, j); } }

// Outputs "2 1"

An output parameter is used for output parameter passing. An output parameter is similar to a reference parameter except that the initial value of the caller-provided argument is unimportant. An output parameter is declared with the out modifier. The following example shows the use of out parameters.
using System;

57

BY: Sharad Pyakurel class Test { static void Divide(int x, int y, out int result, out int remainder) { result = x / y; remainder = x % y; } static void Main() { int res, rem; Divide(10, 3, out res, out rem); Console.WriteLine("{0} {1}", res, rem); } }

// Outputs "3 1"

Constructors:
C# supports both instance and static constructors. An instance constructor is a member that implements the actions required to initialize an instance of a class. A static constructor is a member that implements the actions required to initialize a class itself when it is first loaded. A constructor is declared like a method with no return type and the same name as the containing class. If a constructor declaration includes a static modifier, it declares a static constructor. Otherwise, it declares an instance constructor. Instance constructors can be overloaded. For example, the List<T> class declares two instance constructors, one with no parameters and one that takes an int parameter. Instance constructors are invoked using the new operator. The following statements allocate two List<string> instances using each of the constructors of the List class.
List<string> list1 = new List<string>(); List<string> list2 = new List<string>(10);

Unlike other members, instance constructors are not inherited, and a class has no instance constructors other than those actually declared in the class. If no instance constructor is supplied for a class, then an empty one with no parameters is automatically provided. A Constructor name must be same as that of its class name. It is declared with no return type(not even void) Syntax;
public class MyClass { public MyClass() //Constructor { } } Parameterized Constructor: public class MyNumber { private int _number; public MyNumber() { } public MyNumber(int pNumber) //Constructor with parameter {

57

BY: Sharad Pyakurel this._number = pNumber; } }

Properties:
Properties are a natural extension of fields. Both are named members with associated types, and the syntax for accessing fields and properties is the same. However, unlike fields, properties do not denote storage locations. Instead, properties have accessors that specify the statements to be executed when their values are read or written. A property is declared like a field, except that the declaration ends with a get accessor and/or a set accessor written between the delimiters { and } instead of ending in a semicolon. A property that has both a get accessor and a set accessor is a read-write property, a property that has only a get accessor is a read-only property, and a property that has only a set accessor is a write-only property. A get accessor corresponds to a parameterless method with a return value of the property type. Except as the target of an assignment, when a property is referenced in an expression, the get accessor of the property is invoked to compute the value of the property. A set accessor corresponds to a method with a single parameter named value and no return type. When a property is referenced as the target of an assignment or as the operand of ++ or --, the set accessor is invoked with an argument that provides the new value. The List<T> class declares two properties, Count and Capacity, which are read-only and read-write, respectively. The following is an example of use of these properties.
List<string> names = new List<string>(); names.Capacity = 100; // Invokes set accessor int i = names.Count; // Invokes get accessor int j = names.Capacity; // Invokes get accessor

Similar to fields and methods, C# supports both instance properties and static properties. Static properties are declared with the static modifier, and instance properties are declared without it. The accessor(s) of a property can be virtual. When a property declaration includes a virtual, abstract, or override modifier, it applies to the accessor(s) of the property. Eg:
public class Employee { private string _firstName; private string _address; //First Name Property public string FirstName { get { return _firstName; } set { _firstName = value; } } //Address Property public string Address { get { return _address; } set { _address = value; } } }

Testing the class


public partial class Form1 : Form

57

BY: Sharad Pyakurel { Employee emp = new Employee(); public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { emp.FirstName = "Hari"; emp.Address = "Kathmandu"; MessageBox.Show(emp.FirstName + "," + emp.Address); } }

Indexers:
An indexer is a member that enables objects to be indexed in the same way as an array. An indexer is declared like a property except that the name of the member is this followed by a parameter list written between the delimiters [ and ]. The parameters are available in the accessor(s) of the indexer. Similar to properties, indexers can be read-write, read-only, and write-only, and the accessor(s) of an indexer can be virtual. The List class declares a single read-write indexer that takes an int parameter. The indexer makes it possible to index List instances with int values. For example
List<string> names = new List<string>(); names.Add("Liz"); names.Add("Martha"); names.Add("Beth"); for (int i = 0; i < names.Count; i++) { string s = names[i]; names[i] = s.ToUpper(); }

Indexers can be overloaded, meaning that a class can declare multiple indexers as long as the number or types of their parameters differ.

Events:
An event is a member that enables a class or object to provide notifications. An event is declared like a field except that the declaration includes an event keyword and the type must be a delegate type. Within a class that declares an event member, the event behaves just like a field of a delegate type (provided the event is not abstract and does not declare accessors). The field stores a reference to a delegate that represents the event handlers that have been added to the event. If no event handles are present, the field is null. The List<T> class declares a single event member called Changed, which indicates that a new item has been added to the list. The Changed event is raised by the OnChanged virtual method, which first checks whether the event is null (meaning that no handlers are present). The notion of raising an event is precisely equivalent to invoking the delegate represented by the eventthus, there are no special language constructs for raising events. Clients react to events through event handlers. Event handlers are attached using the += operator and removed using the -= operator. The following example attaches an event handler to the Changed event of a List<string>.
using System;

57

BY: Sharad Pyakurel class Test { static int changeCount; static void ListChanged(object sender, EventArgs e) { changeCount++; } static void Main() { List<string> names = new List<string>(); names.Changed += new EventHandler(ListChanged); names.Add("Liz"); names.Add("Martha"); names.Add("Beth"); Console.WriteLine(changeCount); // Outputs "3" } }

For advanced scenarios where control of the underlying storage of an event is desired, an event declaration can explicitly provide add and remove accessors, which are somewhat similar to the set accessor of a property.

Destructors:
A destructor is a member that implements the actions required to destruct an instance of a class. Destructors cannot have parameters, they cannot have accessibility modifiers, and they cannot be invoked explicitly. The destructor for an instance is invoked automatically during garbage collection. The garbage collector is allowed wide latitude in deciding when to collect objects and run destructors. Specifically, the timing of destructor invocations is not deterministic, and destructors may be executed on any thread. For these and other reasons, classes should implement destructors only when no other solutions are feasible. The using statement provides a better approach to object destruction. Destructor is called by using ~ sign. For example to destruct the constructor named MyConnection() the systax of destructor declaration is : ~MyConnection()

Structs:
Like classes, structs are data structures that can contain data members and function members, but unlike classes, structs are value types and do not require heap allocation. Calsses are reference type stored in heap but structs are value type stored on the stack. Struct Does not support inheritance. A variable of a struct type directly stores the data of the struct, whereas a variable of a class type stores a reference to a dynamically allocated object. Struct types do not support user-specified inheritance, and all struct types implicitly inherit from type object. Structs are particularly useful for small data structures that have value semantics. Complex numbers, points in a coordinate system, or key-value pairs in a dictionary are all good examples of structs. The use of structs rather than classes for small data structures can make a large difference in the number of memory allocations an application performs. For example, the following program creates and initializes an array of 100 points. With Point implemented as a class, 101 separate objects are instantiatedone for the array and one each for the 100 elements.
class Point { public int x, y; public Point(int x, int y) { this.x = x; this.y = y; } }

57

BY: Sharad Pyakurel class Test { static void Main() { Point[] points = new Point[100]; for (int i = 0; i < 100; i++) points[i] = new Point(i, i); } } An alternative is to make Point a struct. struct Point { public int x, y; public Point(int x, int y) { this.x = x; this.y = y; } }

Now, only one object is instantiatedthe one for the arrayand the Point instances are stored in-line in the array. Struct constructors are invoked with the new operator, but that does not imply that memory is being allocated. Instead of dynamically allocating an object and returning a reference to it, a struct constructor simply returns the struct value itself (typically in a temporary location on the stack), and this value is then copied as necessary. With classes, it is possible for two variables to reference the same object and thus possible for operations on one variable to affect the object referenced by the other variable. With structs, the variables each have their own copy of the data, and it is not possible for operations on one to affect the other. For example, the output produced by the following code fragment depends on whether Point is a class or a struct.
Point a = new Point(10, 10); Point b = a; a.x = 20; Console.WriteLine(b.x);

If Point is a class, the output is 20 because a and b reference the same object. If Point is a struct, the output is 10 because the assignment of a to b creates a copy of the value, and this copy is unaffected by the subsequent assignment to a.x. The previous example highlights two of the limitations of structs. First, copying an entire struct is typically less efficient than copying an object reference, so assignment and value parameter passing can be more expensive with structs than with reference types. Second, except for ref and out parameters, it is not possible to create references to structs, which rules out their usage in a number of situations.

Arrays:
An array is a data structure that contains a number of variables that are accessed through computed indices. The variables contained in an array, also called the elements of the array, are all of the same type, and this type is called the element type of the array. Array types are reference types, and the declaration of an array variable simply sets aside space for a reference to an array instance. Actual array instances are created dynamically at run-time using the new operator. The new operation specifies the length of the new array instance, which is then fixed for the lifetime of the instance. The indices of the elements of an array range from 0 to Length - 1. The new operator automatically initializes the elements of an array to their default value, which, for example, is zero for all numeric types and null for all reference types. The following example creates an array of int elements, initializes the array, and prints out the contents of the array.
using System;

57

BY: Sharad Pyakurel class Test { static void Main() { int[] a = new int[10]; for (int i = 0; i < a.Length; i++) { a[i] = i * i; } for (int i = 0; i < a.Length; i++) { Console.WriteLine("a[{0}] = {1}", i, a[i]); } } }

This example creates and operates on a single-dimensional array. C# also supports multi-dimensional arrays. The number of dimensions of an array type, also known as the rank of the array type, is one plus the number of commas written between the square brackets of the array type. The following example allocates a one-dimensional, a two-dimensional, and a three-dimensional array.
int[] a1 = new int[10]; int[,] a2 = new int[10, 5]; int[,,] a3 = new int[10, 5, 2];

The a1 array contains 10 elements, the a2 array contains 50 (10 5) elements, and the a3 array contains 100 (10 5 2) elements. The element type of an array can be any type, including an array type. An array with elements of an array type is sometimes called a jagged array because the lengths of the element arrays do not all have to be the same. The following example allocates an array of arrays of int:
int[][] a = new int[3][]; a[0] = new int[10]; a[1] = new int[5]; a[2] = new int[20];

The first line creates an array with three elements, each of type int[] and each with an initial value of null. The subsequent lines then initialize the three elements with references to individual array instances of varying lengths. The new operator permits the initial values of the array elements to be specified using an array initializer, which is a list of expressions written between the delimiters { and }. The following example allocates and initializes an int[] with three elements.
int[] a = new int[] {1, 2, 3};

Note that the length of the array is inferred from the number of expressions between { and }. Local variable and field declarations can be shortened further such that the array type does not have to be restated.
int[] a = {1, 2, 3};

Both of the previous examples are equivalent to the following:


int[] t = new int[3]; t[0] = 1; t[1] = 2; t[2] = 3; int[] a = t;

Encapsulation:
Encapsulation is the procedure of covering up of data and functions into a single unit(Called class). Encapsulation is needed to prevent the code(data) from accidential corruption. Encapsulation can be done by two ways: By using mutator-accessor method and by using properties.

57

BY: Sharad Pyakurel Using Method: Consider a class Department, here we define accessor(get Methods) and Mutator(set method). using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace CCharpTest { public class Department { private string _departmentName; //Accessor Method public string GetDepartment() { return _departmentName; } //Mutator Method public void SetDepartment(string pDeptName) { _departmentName = pDeptName; } } }

Encapsulation using Properties Properties contains get and set accessors. The get accessor returns the value of some property field. The set accessor sets the value of some property field with the content of value. Property having only get accessor is called Readonly property and property having only set accessor is called writeonly property.

using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace CCharpTest { public class Department { private string _departmentName; public string GetDepartmentName { get { return _departmentName; } } public string SetDepartmentName { set { _departmentName = value; } } } }

INHERITANCE
57

BY: Sharad Pyakurel

A class inherits the members of its direct base class type. Inheritance means that a class implicitly contains all members of its direct base class type, except for the instance constructors, destructors and static constructors of the base class. Some important aspects of inheritance are: Inheritance is transitive. If C is derived from B, and B is derived from A, then C inherits the members declared in B as well as the members declared in A. A derived class extends its direct base class. A derived class can add new members to those it inherits, but it cannot remove the definition of an inherited member. Instance constructors, destructors, and static constructors are not inherited, but all other members are, regardless of their declared accessibility. However, depending on their declared accessibility, inherited members might not be accessible in a derived class. A derived class can hide inherited members by declaring new members with the same name or signature. Note however that hiding an inherited member does not remove that memberit merely makes that member inaccessible directly through the derived class. An instance of a class contains a set of all instance fields declared in the class and its base classes, and an implicit conversion exists from a derived class type to any of its base class types. Thus, a reference to an instance of some derived class can be treated as a reference to an instance of any of its base classes. A class can declare virtual methods, properties, and indexers, and derived classes can override the implementation of these function members. This enables classes to exhibit polymorphic behavior wherein the actions performed by a function member invocation varies depending on the run-time type of the instance through which that function member is invoked. using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace CCharpTest { public class Department { public string GetEmployeeDepartment(int pDeptID) { return GetDeptNmeByID(pDeptID); } private string GetDeptNmeByID(int dptid) { string deptName = string.Empty; switch (dptid) { case 1: deptName= "Administration";

57

BY: Sharad Pyakurel

break; case 2: deptName = "Production"; break; default: deptName = string.Empty; break; } return deptName; } } public class Employee:Department { private void LoadEmpDepartment() { GetEmployeeDepartment(1); } } }

Virtual, override, and abstract methods:


When an instance method declaration includes a virtual modifier, the method is said to be a virtual method. When no virtual modifier is present, the method is said to be a non-virtual method. When a virtual method is invoked, the run-time type of the instance for which that invocation takes place determines the actual method implementation to invoke. In a nonvirtual method invocation, the compiletime type of the instance is the determining factor. A virtual method can be overridden in a derived class. When an instance method declaration includes an override modifier, the method overrides an inherited virtual method with the same signature. Whereas a virtual method declaration introduces a new method, an override method declaration specializes an existing inherited virtual method by providing a new implementation of that method. An abstract method is a virtual method with no implementation. An abstract method is declared with the abstract modifier and is permitted only in a class that is also declared abstract. An abstract method must be overridden in every non-abstract derived class. The following example declares an abstract class, Expression, which represents an expression tree node, and three derived classes, Constant, VariableReference, and Operation, which implement expression tree nodes for constants, variable references, and arithmetic operations.
using System; using System.Collections; public abstract class Expression { public abstract double Evaluate(Hashtable vars); }

57

BY: Sharad Pyakurel public class Constant: Expression { double value; public Constant(double value) { this.value = value; } public override double Evaluate(Hashtable vars) { return value; } } public class VariableReference: Expression { string name; public VariableReference(string name) { this.name = name; } public override double Evaluate(Hashtable vars) { object value = vars[name]; if (value == null) { throw new Exception("Unknown variable: " + name); } return Convert.ToDouble(value); } } public class Operation: Expression { Expression left; char op; Expression right; public Operation(Expression left, char op, Expression right) { this.left = left; this.op = op; this.right = right; } public override double Evaluate(Hashtable vars) { double x = left.Evaluate(vars); double y = right.Evaluate(vars); switch (op) { case '+': return x + y; case '-': return x - y; case '*': return x * y; case '/': return x / y; } throw new Exception("Unknown operator"); } }

The previous four classes can be used to model arithmetic expressions. For example, using instances of these classes, the expression x + 3 can be represented as follows.
Expression e = new Operation( new VariableReference("x"), '+', new Constant(3));

The Evaluate method of an Expression instance is invoked to evaluate the given expression and produce a double value. The method takes as an argument a Hashtable that contains variable names (as keys of the entries) and values (as values of the entries). The Evaluate method is a virtual abstract method, meaning that non-abstract derived classes must override it to provide an actual implementation.

57

BY: Sharad Pyakurel

A Constants implementation of Evaluate simply returns the stored constant. A VariableReferences implementation looks up the variable name in the hashtable and returns the resulting value. An Operations implementation first evaluates the left and right operands (by recursively invoking their Evaluate methods) and then performs the given arithmetic operation. The following program uses the Expression classes to evaluate the expression x * (y + 2) for different values of x and y.
using System; using System.Collections; class Test { static void Main() { Expression e = new Operation( new VariableReference("x"), '*', new Operation( new VariableReference("y"), '+', new Constant(2) ) ); Hashtable vars = new Hashtable(); vars["x"] = 3; vars["y"] = 5; Console.WriteLine(e.Evaluate(vars)); vars["x"] = 1.5; vars["y"] = 9; Console.WriteLine(e.Evaluate(vars)); } }

// Outputs "21"

// Outputs "16.5"

Method overloading:
Method overloading permits multiple methods in the same class to have the same name as long as they have unique signatures. When compiling an invocation of an overloaded method, the compiler uses overload resolution to determine the specific method to invoke. Overload resolution finds the one method that best matches the arguments or reports an error if no single best match can be found. The following example shows overload resolution in effect. The comment for each invocation in the Main method shows which method is actually invoked.
class Test { static void F() { Console.WriteLine("F()"); } static void F(object x) { Console.WriteLine("F(object)"); } static void F(int x) { Console.WriteLine("F(int)"); } static void F(double x) { Console.WriteLine("F(double)"); }

57

BY: Sharad Pyakurel static void F<T>(T x) { Console.WriteLine("F<T>(T)"); } static void F(double x, double y) { Console.WriteLine("F(double, double)"); } static void Main() { F(); F(1); F(1.0); F("abc"); F((double)1); F((object)1); F<int>(1); F(1, 1); } // Invokes F() // Invokes F(int) // Invokes F(double) // Invokes F(object) // Invokes F(double) // Invokes F(object) // Invokes F<T>(T) // Invokes F(double, double) }

As shown by the example, a particular method can always be selected by explicitly casting the arguments to the exact parameter types and/or explicitly supplying type arguments.

57

BY: Sharad Pyakurel

INTERFACE
An interface defines a contract. A class or struct that implements an interface must adhere to its contract. An interface may inherit from multiple base interfaces, and a class or struct may implement multiple interfaces. Interfaces can contain methods, properties, events, and indexers. The interface itself does not provide implementations for the members that it defines. The interface merely specifies the members that must be supplied by classes or structs that implement the interface. Syntax;
//Interface Declaration interface IMyInterface { void HasToBeEmplemented(); } public class MyClass : IMyInterface { void HasToBeEmplemented() //Interface implementation { } }

The following example is based on Bank Account. Assume there are many companies that may implement bank accounts but they have all mutually agreed that any classes that represent bank accounts will implement an interface IBankAccount , which exposes methods to deposit or withdraw money and property to return balance. Firstly we need to define interface IBankAccount using System; using System.Collections.Generic; using System.Text; namespace BankAcc { public interface IBankAccount { void PayIn(decimal amount); bool Withdraw(decimal amount); decimal Balance { get; } } } - Add a Class SaverAccount(which belong to LaxmiBank) and Write thefollowing codes in this class:

57

BY: Sharad Pyakurel

using System; using System.Collections.Generic; using System.Text; namespace BankAcc.LaxmiBank { public class SaverAccount:IBankAccount { private decimal balance; public void PayIn(decimal amount) { balance += amount; } public bool Withdraw(decimal amount) { if (balance >= amount) { balance -= amount; return true; } Console.WriteLine("Withraw Attempt Failed"); return false; } public decimal Balance { get { return balance;} } public override string ToString() { return string.Format("Laxmi Bank Saver: Balance={0,6:c}",balance); } } } -Add a next class GoldAccount(Which belong to Investment Bank) and write the following code:

57

BY: Sharad Pyakurel

using System; using System.Collections.Generic; using System.Text; namespace BankAcc.InvestmentBank { public class GoldAccount:IBankAccount { private decimal balance; public void PayIn(decimal amount) { balance += amount; } public bool Withdraw(decimal amount) { if (balance >= amount) { balance -= amount; return true; } Console.WriteLine("Withraw Attempt Failed"); return false; } public decimal Balance { get { return balance; } } public override string ToString() { return string.Format("Laxmi Bank Saver: Balance={0,6:c}", balance); } } } -Finally to test these classes and Interface write the following codes in the main method using System;

57

BY: Sharad Pyakurel

using System.Collections.Generic; using System.Text; using BankAcc; using BankAcc.LaxmiBank; using BankAcc.InvestmentBank; namespace BankAcc { class Program { static void Main() { IBankAccount laxmiAccount = new SaverAccount(); IBankAccount investmentAccount = new GoldAccount(); laxmiAccount.PayIn(200); laxmiAccount.Withdraw(100); Console.WriteLine(laxmiAccount.ToString()); investmentAccount.PayIn(500); investmentAccount.Withdraw(600); investmentAccount.Withdraw(100); Console.WriteLine(investmentAccount.ToString()); Console.ReadLine(); } } }

The Output of this program will be: Laxmi Bank Saver: Balance=100.00 Withraw Attempt Failed Investment Bank Saver: Balance=400.00

57

BY: Sharad Pyakurel

Derived Interface:
Inheritance in interface is done in the same way that classes do. Following example defines the interface ITransferAccount which has the same features as IBankAccount but also defines a method to transfer money directly to a different account. For eg. -Firstly, add a base interface named IBankAccount using System; using System.Collections.Generic; using System.Text; namespace BankAcc { public interface IBankAccount { void PayIn(decimal amount); bool Withdraw(decimal amount); decimal Balance { get; } } } - Add another interface: Which is derived interface named ITransferAccount using System; using System.Collections.Generic; using System.Text; namespace BankAcc { interface ITransferAccount:IBankAccount { bool TransferTo(IBankAccount destination, decimal amount); } } -Add a class Named SaverAccount and write the following codes: using System;

57

BY: Sharad Pyakurel

using System.Collections.Generic; using System.Text; namespace BankAcc.LaxmiBank { public class SaverAccount:IBankAccount { private decimal balance; public void PayIn(decimal amount) { balance += amount; } public bool Withdraw(decimal amount) { if (balance >= amount) { balance -= amount; return true; } Console.WriteLine("Withraw Attempt Failed"); return false; } public decimal Balance { get { return balance;} } public override string ToString() { return string.Format("Laxmi Bank Saver: Balance={0,6:c}",balance); } } } - Now add a class named CurrentAccount and write the following codes using System; using System.Collections.Generic; using System.Text;

57

BY: Sharad Pyakurel

namespace BankAcc.InvestmentBank { class CurrentAccount:ITransferAccount { private decimal balance; public void PayIn(decimal amount) { balance += amount; } public bool Withdraw(decimal amount) { if (balance >= amount) { balance -= amount; return true; } Console.WriteLine("Withdraw Attempt Failed"); return false; } public decimal Balance { get { return balance; } } public bool TransferTo(IBankAccount destination, decimal amount) { bool result; if ((result = Withdraw(amount)) == true) destination.PayIn(amount); return result; } public override string ToString() { return string.Format("Investment Bank Current Account:Balance={0,6:c}", balance); } }

57

BY: Sharad Pyakurel

} -To Test This Derived Interface write the following codes in main module: using System; using System.Collections.Generic; using System.Text; using BankAcc; using BankAcc.LaxmiBank; using BankAcc.InvestmentBank; namespace BankAcc { class Program { static void Main() { IBankAccount laxmiAccount = new SaverAccount(); ITransferAccount investmentAccount = new CurrentAccount(); laxmiAccount.PayIn(200); investmentAccount.PayIn(500); investmentAccount.TransferTo(laxmiAccount, 100); Console.WriteLine(laxmiAccount.ToString()); Console.WriteLine(investmentAccount.ToString()); Console.ReadLine(); } } }

Implementation of interfaces IComparable, IEnumerable, IDisposable, ICollection:


ICollection:
The ICollection interface is the base interface for classes in the System.Collections namespace.

57

BY: Sharad Pyakurel

IDictionary and IList are more specialized interfaces that are based on the ICollection interface. An IDictionary implementation is a collection of key-and-value pairs, like the Hashtable class. An IList implementation is a collection of values that can be sorted and whose members can be accessed by index, like the ArrayList class. Properties: Count IsSynchronize d SyncRoot Read-Only, It is used for getting the number of elements contained in the ICollection. When implemented by a class, gets a value indicating whether access to the ICollection is synchronized (thread-safe). Read-only, When implemented by a class, gets an object that can be used to synchronize access to the ICollection.

Mathods: CopyTo(): When implemented by a class, copies the elements of the ICollection to anArray, starting at a particular Array index.

Example: using System; using System.Collections; namespace BookCollection { public class Collection : ICollection { private int NumberOfBooks; private string[] books; public Collection() { NumberOfBooks = 0; books = new string[5]; } public virtual int Count { get { return NumberOfBooks; } } public virtual void CopyTo(Array items, int index) { string[] bks = new string[Count]; for (int i = 0; i < Count; i++) bks[i] = books[i]; items = bks; } public virtual object SyncRoot { get { return this; } } public virtual bool IsSynchronized {

57

BY: Sharad Pyakurel

get { return false; } } public IEnumerator GetEnumerator() { return null; } } }

IEnumerable And IEnumerator:


TheIEnumerable interface contains an abstract member function called GetEnumerator() and return an interface IEnumerator on any success call. This IEnumerator interface will allow us to iterate through any custom collection. Any element in a collection can be retrieved through its index property. But instead of element index, the IEnumerator provides two abstract methods and a property to pull a particular element in a collection. And they are Reset(), MoveNext() and Current. SynTax Of GetEnumerator() Is As: public IEnumerator GetEnumerator() { //return IEnumerator of our Custom Type return(IEnumerator)this; } Syntax Of IEnumerator members is as follows: void Reset() bool MoveNext()

object Current The void Reset() method returns a void type and helps you to position the pointer just before the start point. This resetmethod will also help you to reset the iteration pointer anywhere from the start position. The reset method has to be called after any successive addition, deletion of elements in the collection. public void Reset() { //Get total number of element in a collection length=slist.Count; //Setting the pointer to just before the beginning of collection current=-1; }

The bool MoveNext() method will help you to position the location of the required element in the collection while sending a flag value. And its objective is to inform the caller whether the current position holds any value or not. If it has, then MoveNext will return true or return false in case there is no value. In addition, theMoveNext will help you to position the first element in the collection after calling the reset method public bool MoveNext() {

57

BY: Sharad Pyakurel

//this will increment the counter variable //and will check whether it is exceeding the actual length of our collection return(++current<length); }

The object Current property of IEnumerator interface will return an individual element of a given collection. This property is used to return an element in the collection by using the specified location pointer. public object Current { get { //Here "slist" is the collection and "current" is the location pointer return(slist[current]); } }

Example: using System; using System.Collections; public class Person { public Person(string fName, string lName) { this.firstName = fName; this.lastName = lName; } public string firstName; public string lastName; } public class People : IEnumerable { private Person[] _people; public People(Person[] pArray) { _people = new Person[pArray.Length]; for (int i = 0; i < pArray.Length; i++) { _people[i] = pArray[i]; } } IEnumerator IEnumerable.GetEnumerator() { return (IEnumerator) GetEnumerator(); } public PeopleEnum GetEnumerator() {

57

BY: Sharad Pyakurel

return new PeopleEnum(_people); } } public class PeopleEnum : IEnumerator { public Person[] _people; // Enumerators are positioned before the first element // until the first MoveNext() call. int position = -1; public PeopleEnum(Person[] list) { _people = list; } public bool MoveNext() { position++; return (position < _people.Length); } public void Reset() { position = -1; } object IEnumerator.Current { get { return Current; } } public Person Current { get { try { return _people[position]; } catch (IndexOutOfRangeException) { throw new InvalidOperationException(); } } } } class App { static void Main() { Person[] peopleArray = new Person[3]

57

BY: Sharad Pyakurel

{ new Person("John", "Smith"), new Person("Jim", "Johnson"), new Person("Sue", "Rabon"), }; People peopleList = new People(peopleArray); foreach (Person p in peopleList) Console.WriteLine(p.firstName + " " + p.lastName); } }

IComparable Interface:
This interface is used to compare two objects by using CompareTo() Method. Following class implements IComparable<Employee>, which means an Employee instance can be compared with other Employee instances. The Employee class has two instance properties: Salary and Name. It also provides the CompareTo(Employee) method and the ToString method. using System; using System.Collections.Generic; class Employee : IComparable<Employee> { public int Salary { get; set; } public string Name { get; set; } public int CompareTo(Employee other) { // Alphabetic sort if salary is equal. [A to Z] if (this.Salary == other.Salary) { return this.Name.CompareTo(other.Name); } // Default to salary sort. [High to low] return other.Salary.CompareTo(this.Salary); } public override string ToString() { // String representation. return this.Salary.ToString() + "," + this.Name; } }

57

BY: Sharad Pyakurel

class Program { static void Main() { List<Employee> list = new List<Employee>(); list.Add(new Employee() { Name = "Steve", Salary = 10000 }); list.Add(new Employee() { Name = "Janet", Salary = 10000 }); list.Add(new Employee() { Name = "Andrew", Salary = 10000 }); list.Add(new Employee() { Name = "Bill", Salary = 500000 }); list.Add(new Employee() { Name = "Lucy", Salary = 8000 });

// Uses IComparable.CompareTo() list.Sort();

// Uses Employee.ToString foreach (var element in list) { Console.WriteLine(element); } } } OutPut: 500000,Bill 10000,Andrew 10000,Janet 10000,Steve 8000,Lucy

Difference Between Abstract Class And Interface:


When we create an interface, we are basically creating a set of methods without any implementation that must be overridden by the implemented classes. The advantage is that it provides a way for a class to be a part of two classes: one from inheritance hierarchy and one from the interface. When we create an abstract class, we are creating a base class that might have one or more completed methods but at least one or more methods are left uncompleted and declared abstract. If all the methods of an abstract class are uncompleted then it is same as an interface. The purpose of an abstract class is to provide a base class definition for

57

BY: Sharad Pyakurel how a set of derived classes will work and then allow the programmers to fill the implementation in the derived classes.

Abstract Class Employee


using System; namespace AbstractsANDInterfaces { /// /// Summary description for Employee. /// public abstract class Employee { //we can have fields and properties //in the Abstract class protected String id; protected String lname; protected String fname; //properties public abstract String ID { get; set; } public abstract String FirstName { get; set; } public abstract String LastName { get; set; } //completed methods

public String Update() { return "Employee " + id + " " + lname + " " + fname + " updated"; } //completed methods public String Add()

57

BY: Sharad Pyakurel

{ return "Employee " + id + " " + lname + " " + fname + " added"; } //completed methods public String Delete() { return "Employee " + id + " " + lname + " " + fname + " deleted"; } //completed methods public String Search() { return "Employee " + id + " " + lname + " " + fname + " found"; } //abstract method that is different //from Fulltime and Contractor //therefore i keep it uncompleted and //let each implementation //complete it the way they calculate the wage. public abstract String CalculateWage(); } }

Interface IEmployee
using System; namespace AbstractsANDInterfaces { /// <summary> /// Summary description for IEmployee. /// </summary> public interface IEmployee { //cannot have fields. uncommenting //will raise error! // // // protected String id; protected String lname; protected String fname;

57

BY: Sharad Pyakurel

//just signature of the properties //and methods. //setting a rule or contract to be //followed by implementations. String ID { get; set; } String FirstName { get; set; } String LastName { get; set; } // cannot have implementation // cannot have modifiers public // etc all are assumed public // cannot have virtual String Update(); String Add(); String Delete(); String Search(); String CalculateWage(); } }

Inherited Objects
Emp_Fulltime:
using System; namespace AbstractsANDInterfaces { /// /// Summary description for Emp_Fulltime. /// //Inheriting from the Abstract class

57

BY: Sharad Pyakurel

public class Emp_Fulltime : Employee { //uses all the properties of the //Abstract class therefore no //properties or fields here! public Emp_Fulltime() { } public override String ID { get { return id; } set { id = value; } } public override String FirstName { get { return fname; } set { fname = value; } } public override String LastName { get { return lname; } set { lname = value; } } //common methods that are //implemented in the abstract class public new String Add() {

57

BY: Sharad Pyakurel

return base.Add(); } //common methods that are implemented //in the abstract class public new String Delete() { return base.Delete(); } //common methods that are implemented //in the abstract class public new String Search() { return base.Search(); } //common methods that are implemented //in the abstract class public new String Update() { return base.Update(); } //abstract method that is different //from Fulltime and Contractor //therefore I override it here. public override String CalculateWage() { return "Full time employee " + base.fname + " is calculated " + "using the Abstract class..."; } } }

Emp_Fulltime2:
using System; namespace AbstractsANDInterfaces { /// /// Summary description for Emp_fulltime2. /// //Implementing the interface public class Emp_fulltime2 : IEmployee {

57

BY: Sharad Pyakurel

//All the properties and //fields are defined here! protected String id; protected String lname; protected String fname; public Emp_fulltime2() { // // TODO: Add constructor logic here // } public String ID { get { return id; } set { id = value; } } public String FirstName { get { return fname; } set { fname = value; } } public String LastName { get { return lname; } set { lname = value; } } //all the manipulations including Add,Delete,

57

BY: Sharad Pyakurel

//Search, Update, Calculate are done //within the object as there are not //implementation in the Interface entity. public String Add() { return "Fulltime Employee " + fname + " added."; } public String Delete() { return "Fulltime Employee " + fname + " deleted."; } public String Search() { return "Fulltime Employee " + fname + " searched."; } public String Update() { return "Fulltime Employee " + fname + " updated."; } //if you change to Calculatewage(). //Just small 'w' it will raise //error as in interface //it is CalculateWage() with capital 'W'. public String CalculateWage() { return "Full time employee " + fname + " caluculated using " + "Interface."; } } }

Code Testing
//This is the sub that tests both //implementations using Interface and Abstract private void InterfaceExample_Click(object sender, System.EventArgs e) {

57

BY: Sharad Pyakurel

try { IEmployee emp; Emp_fulltime2 emp1 = new Emp_fulltime2(); emp = emp1; emp.ID = "2234"; emp.FirstName= "Rahman" ; emp.LastName = "Mahmoodi" ; //call add method od the object MessageBox.Show(emp.Add().ToString()); //call the CalculateWage method MessageBox.Show(emp.CalculateWage().ToString()); } catch(Exception ex) { MessageBox.Show(ex.Message); } } private void cmdAbstractExample_Click(object sender, System.EventArgs e) { Employee emp; emp = new Emp_Fulltime(); emp.ID = "2244"; emp.FirstName= "Maria" ; emp.LastName = "Robinlius" ; MessageBox.Show(emp.Add().ToString()); //call the CalculateWage method MessageBox.Show(emp.CalculateWage().ToString()); }

DELEGATE AND EVENTS


A delegate type represents references to methods with a particular parameter list and return type. Delegates make it possible to treat methods as entities that can be assigned to variables and passed as parameters. Delegates are similar to the concept of function pointers found in some other languages, but unlike function pointers, delegates are object-oriented and type-safe.

57

BY: Sharad Pyakurel

Delegate is a type that references a method. Once a delegate is assigned a method it behaves exactly like that method. The delegate method can be used like any other methods with parameters and a return value. Delegate is similar to the function pointer in C and C++. The delegate object will basically hold a reference of a function, the function will then can be called via delegate object. A delegate in C# allows us to pass methods of one class to objects to other classes that can call those methods. We can pass method M in class A wrapped in a delegate to class B and class B will be able to call method M in class A. Syntax of delegate Declaration: Public delegate int PerformCalculation(int x, int y);

Delegate Example 1:
-Add a class named Myclass1 and write the following code: using System; using System.Collections.Generic; using System.Text; namespace Delegate { //step1:-Declaring delegate public delegate void MyDelagate(string input); class Myclass1 { //Step2:-Defining methods that match with the signature of delegate declaration public void delegateMethod1(string input) { Console.WriteLine("This is delegateMethod1 and the input to the method is {0}", input); Console.ReadLine(); } public void delegateMethod2(string input) { Console.WriteLine("This is delegateMethod2 and the input to the delegate is {0}", input); Console.ReadLine(); } } //Step3:- Creating the delegate object and assigning methods to those delegate objects

57

BY: Sharad Pyakurel

class Myclass2 { public MyDelagate createDelegate() { Myclass1 c2 = new Myclass1(); MyDelagate d1 = new MyDelagate(c2.delegateMethod1); MyDelagate d2 = new MyDelagate(c2.delegateMethod2); MyDelagate d3 = d1 + d2; return d3; } } //Step4:-Calling the methods via delegate objects class Myclass3 { public void callDelegate(MyDelagate d, string input) { d(input); } } } -To test this delegate write the following codes in main module: using System; using System.Collections.Generic; using System.Text; namespace Delegate { class Program { static void Main(string[] args) { Myclass2 c2 = new Myclass2(); MyDelagate d = c2.createDelegate(); Myclass3 c3 = new Myclass3(); c3.callDelegate(d, "calling delagate"); }

57

BY: Sharad Pyakurel

} }

Delegate Example 2:
-Add a class named Math and write the following codes: using System; using System.Collections.Generic; using System.Text; namespace Delegate { public delegate int DelegateToMethod(int x,int y); public class Math { public static int Add(int first, int second) { return first + second; } public static int Multiply(int first, int second) { return first * second; } public static int Divide(int first, int second) { return first / second; } } } -To test the delegate write the following program in the main module using System; using System.Collections.Generic; using System.Text;

57

BY: Sharad Pyakurel

namespace Delegate { class Program { static void Main() { int input1, input2; Console.WriteLine("Enter two numbers"); input1 = Convert.ToInt32(Console.ReadLine()); input2 = Convert.ToInt32(Console.ReadLine()); DelegateToMethod aDelegate = new DelegateToMethod(Math.Add); DelegateToMethod mDelegate = new DelegateToMethod(Math.Multiply); DelegateToMethod dDelegate = new DelegateToMethod(Math.Divide); Console.WriteLine("Calling the method Math.Add through aDelegate Object"); Console.WriteLine(aDelegate(input1, input2)); Console.WriteLine("Calling the method Math.Multiply through mDelegate object"); Console.WriteLine(mDelegate(input1, input2)); Console.WriteLine("Calling the method Math.divide through dDelegate object"); Console.WriteLine(dDelegate(input1, input2)); Console.ReadLine(); } } }

Events:
An event is a member that enables a class or object to provide notifications. An event is declared like a field except that the declaration includes an event keyword and the type must be a delegate type. Within a class that declares an event member, the event behaves just like a field of a delegate type (provided the event is not abstract and does not declare accessors). The field stores a reference to a delegate that represents the event handlers that have been added to the event. If no event handles are present, the field is null. The List<T> class declares a single event member called Changed, which indicates that a new item has been added to the list. The Changed event is raised by the OnChanged virtual method, which first checks whether the event is null (meaning that no handlers are present). The notion of raising an event is precisely equivalent to invoking the delegate represented by the eventthus, there are no special language constructs for raising events.

57

BY: Sharad Pyakurel

Clients react to events through event handlers. Event handlers are attached using the += operator and removed using the -= operator. The following example attaches an event handler to the Changed event of a List<string>.
using System; class Test { static int changeCount; static void ListChanged(object sender, EventArgs e) { changeCount++; } static void Main() { List<string> names = new List<string>(); names.Changed += new EventHandler(ListChanged); names.Add("Liz"); names.Add("Martha"); names.Add("Beth"); Console.WriteLine(changeCount); // Outputs "3" } }

For advanced scenarios where control of the underlying storage of an event is desired, an event declaration can explicitly provide add and remove accessors, which are somewhat similar to the set accessor of a property.

Strings And Regular Expressions


String class is defined on System.String namespace. The System.String is specifically designed to store string and allow a large number of operations on the string. String message1=Hello; //Returns Hello;

57

BY: Sharad Pyakurel

Message1+=,There; //Returns Hello, There String message2=message1+ !; //Returns Hello There ! We can use StringBuilder class to build a string. StringBuilder class is defined on System.Text. We can also create an empty string with a given size. StringBuilder sb=new StringBuilder(20); Basic Methods in StringBuilder class are : Append() : Appends string to the current string. AppendFormat(): Appends string with format sb.AppendFormat(My Name is {0},Sharad); Insert() : inserts substring to the current string. Remove() : Removes characters from the current string. Replace() : Replaces all occrances of a character by another character or a substring with another substring in the current string

Regular Experessions:
It is defined in the namespace System.Text.RegularExpressions. It is used to check the specified pattern of the string.
string pattern = @"\bn"; if (Regex.IsMatch("I am sharad", pattern)) { MessageBox.Show("Math Found."); } else { MessageBox.Show("String is not matched"); }

COLLECTIONS
A class consisting of group of similar object is called collection class in .NET. The idea of a collection is that it represents a set of objects that you can access by stepping through each element in turn. We can access the set of objects by using a foreach loop.

57

BY: Sharad Pyakurel

An object is a collection if it is able to supply a reference to a related object, known as enumerator, which is able to step through the item in the collection. A collection must implement the interface System.Collections.IEnumerable. Interface IEnumerable { IEnumerator GetEnumerator(); } The purpose of GetEnumerator() is to return the enumerator object. The interface IEnumerator looks like:
interface IEnumerator { object Current { get; } bool MoveNext(); void Reset(); }

Array List:
An Array List is very similar to an array except that it has ability to grow and shrink. It is represented by class System.Collections.ArrayList. The ArrayList allocates enough memory to store certain numbers of object references, then we can efficiently manipulate these object references. We can add more objects to the ArrayList, it will automatically increase its capacity by allocating a new area of memory. An ArrayList is initialised as : ArrayList ArrayList objArrayList=new ArrayList(); ArrayList(15); We can also initilize an ArrayList by indicating the initial capacity we want. Eg: footballTeam=new We also set the capacity of the ArrayList directly after its initilization with the use of the capacity property. ArrayList objArrayList=new ArrayList(); objArrayList.Capacity=15;
using System; using System.Collections.Generic; using System.Collections; using System.Text; namespace ArrayLis { class Program { static void Main(string[] args) {

57

BY: Sharad Pyakurel ArrayList footballTeam = new ArrayList(); footballTeam.Add("Ram"); footballTeam.Add("Shyam"); footballTeam.Add("Hari"); foreach (string item in footballTeam) { Console.Write(item + "\n"); } Console.ReadLine(); } } }

We can use AddRange() Method to Add an entire collections of Items at a time as shown in following example:

using System; using System.Collections.Generic; using System.Collections; using System.Text; namespace ArrayLis { class Program { static void Main(string[] args) { ArrayList footballTeam = new ArrayList(); footballTeam.Add("Ram"); footballTeam.Add("Shyam"); footballTeam.Add("Hari"); string[] myStringArray = new string[3]; myStringArray[0] = "Shilpa"; myStringArray[1] = "Ayasa"; myStringArray[2] = "Simana"; footballTeam.AddRange(myStringArray); foreach (string item in footballTeam) {

57

BY: Sharad Pyakurel Console.Write(item + "\n"); } Console.ReadLine(); } } }

GENERICS
Generics allow you to define type-safe classes without compromising type safety, performance, or productivity. You implement the server only once as a generic server, while at the same time you can declare and use it with any type. To do that, use the < and > brackets, enclosing a generic type parameter. For example, here is how you define and use a generic stack:

57

BY: Sharad Pyakurel public class Stack<T> { T[] m_Items; public void Push(T item) {...} public T Pop() {...} } Stack<int> stack = new Stack<int>(); stack.Push(1); stack.Push(2); int number = stack.Pop();

Generic Method:
A generic method is a method that is declared with type parameters. In the following example Class MyClass contains a generic method Copy. This accepts two generic list parameters source and destination. Data in the source will be copied to destination.

public class MyClass { public static List<T> Copy<T>(List<T> source, List<T> destination) { foreach (T obj in source) { destination.Add(obj); } return destination; } } Now, List nameList1 and nameList2 will be respectivelly copied to the List finalList private void button1_Click(object sender, EventArgs e) { string[] arNames = { "Ram", "Shyam", "Hari" }; List<string> nameList1 = new List<string>(arNames); string[] arNames2 = { "Sita", "Mina", "Laxmi" }; List<string> nameList2 = new List<string>(arNames2); List<string> finalList = new List<string>(); finalList = MyClass.Copy<string>(nameList1, finalList); StringBuilder sbm = new StringBuilder(); sbm.Remove(0, sbm.Length); sbm.Append("Final List After copying nameList1:"); foreach (string obj in finalList) { sbm.Append("\n\t " + obj.ToString()); } finalList = MyClass.Copy<string>(nameList2, finalList); StringBuilder sb = new StringBuilder(); sb.Remove(0, sb.Length); sb.Append("\nFinal List After Copying nameList2."); foreach (string obj1 in finalList) { sb.Append("\n\t " + obj1.ToString()); } MessageBox.Show(sbm.ToString() + sb.ToString()); }

57

BY: Sharad Pyakurel

Generic Class:
Generic classes are classes that can hold objects of any class. Generic classes encapsulate operations that are not specific to a particular data type. The most common use for generic classes is with collections like linked lists, hash tables, stacks, queues, trees and so on where operations such as adding and removing items from the collection are performed in much the same way regardless of the type of data being stored.

using System; using System.Collections.Generic; using System.Linq; using System.Collections; using System.Text; namespace GenericTest { public class Employee { private string fname; private string lname; private int age; public string FirstName { get { return fname; } set { fname = value; } } public string LastName { get { return lname; } set { lname = value; } } public int Age { get { return age; } set { age = value; } } public Employee(string fname, string lname, int age) { FirstName = fname; LastName = lname; Age = age; } } public class EmployeeList : IEnumerable { private ArrayList alist = new ArrayList(); public int Add(Employee value) { try { return alist.Add(value); } catch (Exception ex) { throw ex; }

57

BY: Sharad Pyakurel } #region IEnumerable Members public IEnumerator GetEnumerator() { try { return alist.GetEnumerator(); } catch (Exception ex) { throw ex; } } #endregion } public class MyCustomList<T> : IEnumerable, IEnumerable<T> { private ArrayList alist = new ArrayList(); public int Add(T value) { try { return alist.Add(value); } catch (Exception ex) { throw ex; } } #region IEnumerable Members public IEnumerator GetEnumerator() { try { return alist.GetEnumerator(); } catch (Exception ex) { throw ex; } } #endregion #region IEnumerable<T> Members IEnumerator<T> IEnumerable<T>.GetEnumerator() { try { return (IEnumerator<T>)alist.GetEnumerator(); } catch (Exception ex) { throw ex; } }

57

BY: Sharad Pyakurel #endregion } } Not To Test Above Defined class

private void button2_Click(object sender, EventArgs e) { Employee Venky = new Employee("Vakateshwar", "Rao", 25); Employee raj = new Employee("Raj", "Kumar", 24); EmployeeList mc = new EmployeeList(); mc.Add(Venky); mc.Add(raj); StringBuilder sb = new StringBuilder(); sb.Remove(0, sb.Length); sb.Append("Using a custom strongly typed EmployeeList"); foreach (Employee s in mc) { sb.AppendFormat("\n\t First Name :{0} ", s.FirstName); sb.AppendFormat("\n\t Last Name : {0}", s.LastName); sb.AppendFormat("\n\t Age : {0}", s.Age); sb.Append("\n"); } ///-------------------------------------------------------MyCustomList<Employee> Employee = new MyCustomList<Employee>(); Employee.Add(Venky); Employee.Add(raj); sb.Append("\n\n Using a list of Employee objects using my custom generics"); foreach (Employee s in Employee) { sb.AppendFormat("\n\t First Name :{0} ", s.FirstName); sb.AppendFormat("\n\t Last Name : {0}", s.LastName); sb.AppendFormat("\n\t Age : {0}", s.Age); sb.Append("\n"); } //-------------------------------------------------------------MyCustomList<int> intlist = new MyCustomList<int>(); intlist.Add(1); intlist.Add(2); sb.Append("\n\n Using a list of String values using my custom generics"); foreach (int i in intlist) { sb.AppendFormat("\n\t Index :{0} ", i.ToString()); } //---------------------------------------------------------------MyCustomList<string> strlist = new MyCustomList<string>(); strlist.Add("One"); strlist.Add("Two"); sb.Append("\n\n Using a list of int values using my custom generics"); foreach (string str in strlist) { sb.AppendFormat("\n\t Index : {0}", str); } MessageBox.Show(sb.ToString());

57

BY: Sharad Pyakurel }

THREADING
Thread is a light weight process. A single process can have multiple threads. Threading is technique of running multiple processes within an application without interfering each other. In .NET thread related classes are defined on System.Threading namespace.
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; namespace ThreadingConsole { class Program { static void Main(string[] args) { Thread thisThread = Thread.CurrentThread; thisThread.Name = "Main Thread"; ThreadStart workStart = new ThreadStart(DisplayTimes); Thread workerThread = new Thread(workStart); workerThread.Name = "Worker"; workerThread.Start(); DisplayDates(); Console.WriteLine("Main Thread Finished "); Console.ReadLine(); } static void DisplayTimes() { Thread thisThread = Thread.CurrentThread; string name = thisThread.Name; Console.WriteLine("Starting Thread:" + name); for (int i = 0; i <= 10; i++) { Console.WriteLine("Current Time " + DateTime.Now.ToLongTimeString()); Thread.Sleep(2000); } Console.WriteLine("Worker Thread Finished."); } static void DisplayDates() { Thread dateThread = Thread.CurrentThread; string name = dateThread.Name; Console.WriteLine("Starting Thread:" + name); for (int i = 0; i <= 10; i++) {

57

BY: Sharad Pyakurel Console.WriteLine("Current Date " + DateTime.Now.ToShortDateString()); Thread.Sleep(1000); } } } }

Threading Using ThreadPool Class:


Thread pooling enables you to use threads more efficiently by providing your application with a pool of worker threads that are managed by the system. One thread monitors the status of several wait operations queued to the thread pool. When a wait operation completes, a worker thread from the thread pool executes the corresponding callback function. The thread pool has a default size of 25 threads per available processor. The number of threads in the thread pool can be changed using the SetMaxThreads method. Each thread uses the default stack size and runs at the default priority.
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; namespace ThreadingConsole { class Program { static int interval; static void Main(string[] args) { Console.WriteLine("Result Interval At?"); interval = int.Parse(Console.ReadLine()); ThreadPool.QueueUserWorkItem(new WaitCallback(startMethod)); Thread.Sleep(100); ThreadPool.QueueUserWorkItem(new WaitCallback(startMethod)); Console.ReadLine(); } static void startMethod(object stateInfo) { DisplayNumbers("Thread" + DateTime.Now.Millisecond.ToString()); Console.WriteLine("Thread Finished"); } static void DisplayNumbers(string givenThreadName) { Console.WriteLine("Starting Thread " + givenThreadName); for (int i = 1; i <= 8 * interval; i++) { if (i % interval == 0) { Console.WriteLine("Count Reached " + i); Thread.Sleep(1000); } } } } }

Example: Changing Lable Text Dynamically using threading.


Design a form with a lable lblDetails And buttons btnStart And btnStop

57

BY: Sharad Pyakurel using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.Threading; namespace GenericTest { public partial class frmThread : Form { delegate void LabelDelegate(string message); private bool isFinished = false; public frmThread() { InitializeComponent(); } private void btnStart_Click(object sender, EventArgs e) { isFinished = false; StartAnimation(); } private void StartAnimation() { ThreadStart th1 = new ThreadStart(ShowTest1); Thread t1 = new Thread(th1); t1.Start(); } private void ShowTest1() { List<string> lst = GetDetailList(); foreach (string s in lst) { UpdatingLabel1(s); Thread.Sleep(1000); } if (!isFinished) { StartAnimation(); } } private void UpdatingLabel1(string msg) { if (this.lblDetails.InvokeRequired) this.lblDetails.Invoke(new LabelDelegate(UpdatingLabel1), new object[] { msg }); else this.lblDetails.Text = msg; } private List<string> GetDetailList() { List<string> detlst = new List<string>(); detlst.Add("Travel Service"); detlst.Add("Education Servide"); detlst.Add("Carier Development");

57

BY: Sharad Pyakurel detlst.Add("Technical Education"); detlst.Add("Motivation Programs"); detlst.Add("Other Facilities"); detlst.Add("Information Service"); return detlst; } private void btnStop_Click(object sender, EventArgs e) { isFinished = true; } } }

Graphics GDI +
GDI+ is next evolution of GDI(Graphics Device Interface). Using GDI objects in earlier versions of Visual Studio was a pain. In Visual Studio .NET, Microsoft has taken care of most of the GDI problems and have made it easy to use. GDI+ resides in System.Drawing.dll assembly. All GDI+ classes are reside in the System.Drawing, System.Text, System.Printing,System.Internal , System.Imaging, System.Drawi ng2D andSystem.Design namespaces.

57

BY: Sharad Pyakurel

The Graphics Class:


The Graphics class encapsulates GDI+ drawing surfaces. Before drawing any object (for example circle, or rectangle) we have to create a surface using Graphics class. Generally we use Paint event of a Form to get the reference of the graphics. Another way is to override OnPaint method. Here is how you get a reference of the Graphics object: private void form1_Paint(object sender, PaintEventArgs e) { Graphics g = e.Graphics; } OR: protected override void OnPaint(PaintEventArgs e) { Graphics g = e.Graphics; } Once you have the Graphics reference, you can call any of this class's members to draw various objects. Here are some of Graphics class's methods: DrawArc DrawBezier DrawBeziers DrawClosedCurve DrawCurve DrawEllipse DrawImage DrawLine DrawPath DrawPie DrawPolygon DrawRectangle DrawString FillEllipse FillPath FillPie FillPolygon FillRectangle FillRectangles FillRegion Draws an arc from the specified ellipse. Draws a cubic bezier curve. Draws a series of cubic Bezier curves. Draws a closed curve defined by an array of points. Draws a curve defined by an array of points. Draws an ellipse. Draws an image. Draws a line. Draws the lines and curves defined by a GraphicsPath. Draws the outline of a pie section. Draws the outline of a polygon. Draws the outline of a rectangle. Draws a string. Fills the interior of an ellipse defined by a bounding rectangle. Fills the interior of a path. Fills the interior of a pie section. Fills the interior of a polygon defined by an array of points. Fills the interior of a rectangle with a Brush. Fills the interiors of a series of rectangles with a Brush. Fills the interior of a Region.

In .NET, GDI+ functionality resides in the System.Drawing.dll. Before you start using GDI+ classes, you must add reference to the System.Drawing.dll and import System.Drawing namespace.

Graphics Objects:
After creating a Graphics object, you can use it draw lines, fill shapes, drawtext and so on. The major objects are: Brush Used to fill enclosed surfaces with patterns,colors, or bitmaps.

57

BY: Sharad Pyakurel

Pen

Used to draw lines and polygons, including rectangles, arcs, and pies

Font Used to describe the font to be used to render text Color Used to describe the color used to render a particular object. In GDI+ color can be alpha blended

The Pen Class:


A pen draws a line of specified width and style. You always use Pen constructor to create a pen. The constructor initializes a new instance of the Pen class. You can initialize it with a color or brush. Initializes a new instance of the Pen class with the specified color. public Pen(Color); Initializes a new instance of the Pen class with the specified Brush. public Pen(Brush); Initializes a new instance of the Pen class with the specified Brush and width. public Pen(Brush, float); Initializes a new instance of the Pen class with the specified Color and Width. public Pen(Color, float); For example: Pen pn = new Pen( Color.Blue ); or Pen pn = new Pen( Color.Blue, 100 ); Some of its most commonly used properties are: Alignment Brush Color Width Gets or sets the alignment for objects drawn with this Pen. Gets or sets the Brush that determines attributes of this Pen. Gets or sets the color of this Pen. Gets or sets the width of this Pen.

The Color Structure:


A Color structure represents an ARGB color. Here are ARGB properties of it: A B G R Gets the alpha component value for this Color. Gets the blue component value for this Color. Gets the green component value for this Color. Gets the red component value for this Color.

You can call the Color members. Each color name (say Blue) is a member of the Color structure. Here is how to use a Color structure: Pen pn = new Pen( Color.Blue );

The Font Class:


The Font class defines a particular format for text such as font type, size, and style attributes. You use font constructor to create a font. Initializes a new instance of the Font class with the specified attributes. public Font(string, float); Initializes a new instance of the Font class from the specified existing Font and FontStyle. public Font(Font, FontStyle);

57

BY: Sharad Pyakurel

Where FontStyle is an enumeration and here are its members: Member Name Bold Italic Regular Strikeout Underline Description Bold text. Italic text. Normal text. Text with a line through the middle. Underlined text.

For example: Graphics g ; Font font = new Font("Times New Roman", 26); Some of its most commonly used properties are: Bold FontFamily Height Italic Name Size SizeInPoints Strikeout Style Underline Unit Gets a value indicating whether this Font is bold. Gets the FontFamily of this Font. Gets the height of this Font. Gets a value indicating whether this Font is Italic. Gets the face name of this Font. Gets the size of this Font. Gets the size, in points, of this Font. Gets a value indicating whether this Font is strikeout (has a line through it). Gets style information for this Font. Gets a value indicating whether this Font is underlined. Gets the unit of measure for this Font.

The Brush Class:


The Brush class is an abstract base class and cannot be instantiated. We always use its derived classes to instantiate a brush object, such as SolidBrush, TextureBrush, RectangleGradientBrush, and LinearGradientBrush. Example: LinearGradientBrush lBrush = new LinearGradientBrush(rect, Color.Red, Color.Yellow,LinearGradientMode.BackwardDiagonal); OR Brush brsh = new SolidBrush(Color.Red), 40, 40, 140, 140); The SolidBrush class defines a brush made up of a single color. Brushes are used to fill graphics shapes such as rectangles, ellipses, pies, polygons, and paths. The TextureBrush encapsulates a Brush that uses an fills the interior of a shape with an image. The LinearGradiantBrush encapsulates both two-color gradients and custom multi-color gradients.

The Rectangle Structure:


public Rectangle(Point, Size); or public Rectangle(int, int, int, int);

57

BY: Sharad Pyakurel

The Rectangle structure is used to draw a rectangle on WinForms. Besides its constructor, the Rectangle structure has following members: Bottom Gets the y-coordinate of the lower-right corner of the rectangular region defined by this Rectangle. Height Left Gets or sets the width of the rectangular region defined by this Rectangle. Gets the x-coordinate of the upper-left corner of the rectangular region defined by this Rectangle. IsEmpty Tests whether this Rectangle has a Width or a Height of 0. Location Gets or sets the coordinates of the upper-left corner of the rectangular region represented by this Rectangle. Right Size Top Width X Y Gets the x-coordinate of the lower-right corner of the rectangular region defined by this Rectangle. Gets or sets the size of this Rectangle. Gets the y-coordinate of the upper-left corner of the rectangular region defined by this Rectangle. Gets or sets the width of the rectangular region defined by this Rectangle. Gets or sets the x-coordinate of the upper-left corner of the rectangular region defined by this Rectangle. Gets or sets the y-coordinate of the upper-left corner of the rectangular region defined by this Rectangle.

Its constructor initializes a new instance of the Rectangle class. Here is the definition: public Rectangle(Point, Size); or public Rectangle(int, int, int, int);

The Point Structure:


This structure is similar to the POINT structure in C++. It represents an ordered pair of x and y coordinates that define a point in a two-dimensional plane. The member x represents the x coordinates and y represents the y coordinates of the plane. Here is how to instantiate a point structure: Point pt1 = new Point( 30, 30); Point pt2 = new Point( 110, 100); Examples:

Drawing a rectangle:
You can override OnPaint event of your form to draw an rectangle. The LinearGradientBrush encapsulates a brush and linear gradient. protected override void OnPaint(PaintEventArgs pe) { Graphics g = pe.Graphics ; Rectangle rect = new Rectangle(50, 30, 100, 100); LinearGradientBrush lBrush = new LinearGradientBrush(rect, Color.Red, Color.Yellow,LinearGradientMode.BackwardDiagonal); g.FillRectangle(lBrush, rect); } The output of the above code looks like

57

BY: Sharad Pyakurel

Drawing an Arc:
DrawArc function draws an arc. This function takes four arguments. First is the Pen. You create a pen by using the Pen class. The Pen constructor takes at least one argument, the color or the brush of the pen. Second argument width of the pen or brush is optional. Pen pn = new Pen( Color.Blue ); or Pen pn = new Pen( Color.Blue, 100 ); The second argument is a rectangle. You can create a rectangle by using Rectangle structure. The Rectangle constructor takes four int type arguments and they are left and right corners of the rectangle. Rectangle rect = new Rectangle(50, 50, 200, 100); protected override void OnPaint(PaintEventArgs pe) { Graphics g = pe.Graphics ; Pen pn = new Pen( Color.Blue ); Rectangle rect = new Rectangle(50, 50, 200, 100); g.DrawArc( pn, rect, 12, 84 ); } The output looks like this:

Drawing a Line:
DrawLine function of the Graphics class draws a line. It takes three parameters, a pen, and two Point class parameters, starting and ending points. Point class constructor takes x, y arguments. protected override void OnPaint(PaintEventArgs pe) { Graphics g = pe.Graphics ; Pen pn = new Pen( Color.Blue ); // Rectangle rect = new Rectangle(50, 50, 200, 100); Point pt1 = new Point( 30, 30); Point pt2 = new Point( 110, 100); g.DrawLine( pn, pt1, pt2 ); } The output looks like this:

57

BY: Sharad Pyakurel

Drawing an Ellipse:
An ellipse( or a circle) can be drawn by using DrawEllipse method. This method takes only two parameters, Pen and rectangle. protected override void OnPaint(PaintEventArgs pe) { Graphics g = pe.Graphics ; Pen pn = new Pen( Color.Blue, 100 ); Rectangle rect = new Rectangle(50, 50, 200, 100); g.DrawEllipse( pn, rect ); } The output looks like this:

The FillPath:
Drawing bazier curves is little more complex than other objects. protected override void OnPaint(PaintEventArgs pe) { Graphics g = pe.Graphics; g.FillRectangle(new SolidBrush(Color.White), ClientRectangle); GraphicsPath path = new GraphicsPath(new Point[] { new Point(40, 140), new Point(275, 200), new Point(105, 225), new Point(190, 300), new Point(50, 350), new Point(20, 180), }, new byte[] { (byte)PathPointType.Start, (byte)PathPointType.Bezier, (byte)PathPointType.Bezier, (byte)PathPointType.Bezier, (byte)PathPointType.Line, (byte)PathPointType.Line, }); PathGradientBrush pgb = new PathGradientBrush(path); pgb.SurroundColors = new Color[] { Color.Green,Color.Yellow,Color.Red, Color.Blue, Color.Orange, Color.White, };

57

BY: Sharad Pyakurel

g.FillPath(pgb, path); } The output looks like this:

Drawing Text and Strings:


You can override OnPaint event of your form to draw an rectangle. The LinearGradientBrush encapsulates a brush and linear gradient. protected override void OnPaint(PaintEventArgs pe) { Font fnt = new Font("Verdana", 16); Graphics g = pe.Graphics; g.DrawString("GDI+ World", fnt, new SolidBrush(Color.Red), 14,10); } The output looks like this:

57

BY: Sharad Pyakurel

LINQ (Language-Integrated Query)


LINQ (Language Integrated Query) is a Microsoft programming model and methodology that essentially adds formal query capabilities into Microsoft .NET-based programming languages. LINQ offers a compact, expressive, and intelligible syntax for manipulating data. The real value of LINQ comes from its ability to apply the same query to an SQL database, a Dataset, an array of objects in memory and to many other types of data as well.

Advantages of LINQ:
1. LINQ offers an object-based, language-integrated way to query over data no matter where that data came from. So through LINQ we can query database,XML as well as collections. 2. Compile time syntax checking 3. It allows you to query collections like arrays, enumerable classes etc in the native language of your application, like VB or C# in much the same way as you would query a database using SQL Example:
EmployeeShift Class

namespace LinqExample { //Employee Shift Enum public enum EmployeeShift { Morning = 0, Day, Evening, Night } //Gender Enum public enum Gender { Male = 0, Female } public class CEmployee { #region Member Variables private int _empID; private string _empName; private string _empAddress; private EmployeeShift _shift; private Gender _gender; private decimal _salary; #endregion #region Properties public int EmpID { get { return _empID; } set { _empID = value; } } public string EmpName { get { return _empName; }

57

BY: Sharad Pyakurel set { _empName = value; } } public string EmpAddress { get { return _empAddress; } set { _empAddress = value; } } public EmployeeShift Shift { get { return _shift; } set { _shift = value; } } public Gender Gender { get { return _gender; } set { _gender = value; } } public decimal Salary { get { return _salary; } set { _salary = value; } } //Constructor public CEmployee(int pEmpID, string pEmpName, string pEmpAddress, EmployeeShift pShift, Gender pGender, decimal pSalary) { this.EmpID = pEmpID; this.EmpName = pEmpName; this.EmpAddress = pEmpAddress; this.Shift = pShift; this.Gender = pGender; this.Salary = pSalary; } #endregion } }

CEmployeeDetails Class

using System.Collections.Generic; namespace LinqExample { public class CEmployeeDetails { private List<CEmployee> _employees = new List<CEmployee>(); public List<CEmployee> Employees { get { _employees.Add(new CEmployee(1, "Sharad Pyakurel", "Kathmandu", EmployeeShift.Morning, Gender.Male, 35000)); _employees.Add(new CEmployee(2, "Hari Krishna", "Pokhara", EmployeeShift.Morning, Gender.Male, 17000)); _employees.Add(new CEmployee(3, "Sita Devi Sharma", "Lalitpur", EmployeeShift.Day, Gender.Female, 15000));

57

BY: Sharad Pyakurel _employees.Add(new CEmployee(4, "Ramesh Adhikari", "Kathmandu", EmployeeShift.Evening, Gender.Male, 13000)); _employees.Add(new CEmployee(5, "Sudarshan Poudel", "Bhadrapur", EmployeeShift.Day, Gender.Male, 21000)); _employees.Add(new CEmployee(6, "Sumitra Pyakurel", "Baneshwor", EmployeeShift.Evening, Gender.Female, 25000)); _employees.Add(new CEmployee(7, "Utsab Adhikari", "Bharatpur", EmployeeShift.Day, Gender.Male, 30000)); return _employees; } //set { _employees = value; } } } }

CEmployeePost Class

namespace LinqExample { public class CEmployeePost { private List<CPosts> _EmpPostDetails = new List<CPosts>(); public List<CPosts> EmpPostDetails { get { _EmpPostDetails.Add(new CPosts(1, "CEO")); _EmpPostDetails.Add(new CPosts(2, "Officer")); _EmpPostDetails.Add(new CPosts(3, "Officer")); _EmpPostDetails.Add(new CPosts(4, "General Manager")); _EmpPostDetails.Add(new CPosts(5, "Sineor manager")); _EmpPostDetails.Add(new CPosts(6, "Deputy General Manager")); _EmpPostDetails.Add(new CPosts(7, "Senior DGM")); return _EmpPostDetails; } //set { _employees = value; } } } }

CPost Class

namespace LinqExample { public class CPosts { #region Member Variables private int _empID; private string _postName; #endregion #region Properties public int EmpID { get { return _empID; } set { _empID = value; } } public string PostName

57

BY: Sharad Pyakurel { get { return _postName; } set { _postName = value; } } #endregion #region Constructor public CPosts(int pEmpID, string pPostName) { this.EmpID = pEmpID; this.PostName = pPostName; } #endregion } }

Implementing Above Classes using LINQ

using System.Collections.Generic; namespace LinqExample { public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { }

//Querrying Data from array using simple LINQ


protected void btnBasicCities_Click(object sender, EventArgs e) { string[] cities = { "Kathmenu", "Lalitpur", "Banepa Kavre", "Bhaktapur", "Pokhara", "Janakpur", "Birjung", "Bharatpur", "Nepaljung", "Butwal", "Dharan" }; Grid1.DataSource = from city in cities where city.Length > 4 orderby city select city.ToUpper(); }

//using Where Condition in LINQ to Select Employees having salary greater than supplied value
protected void btnHavingSalGt_Click(object sender, EventArgs e) { CEmployeeDetails empd = new CEmployeeDetails(); Grid1.DataSource = from emps in empd.Employees where emps.Salary > Convert.ToDecimal(txtSalaryGt.Text.Trim()) orderby emps.EmpID, emps.Salary select emps; }

//Querring only required data using LINQ


protected void btnNameAddressSalaryOfDayEmp_Click(object sender, EventArgs e)

57

BY: Sharad Pyakurel { CEmployeeDetails empd = new CEmployeeDetails(); Grid1.DataSource = from emps in empd.Employees where emps.Shift == EmployeeShift.Morning orderby emps.EmpID, emps.Salary select new { emps.EmpName, emps.EmpAddress, emps.Salary, WorkingShift = GetEnumShiftString(emps.Shift), Remarks = "No-Remarks" }; //Here WorkingShift, Remarks are Anonymus Type Member }

//Getting String from Enum


private string GetEnumShiftString(EmployeeShift shft) { switch (shft) { case EmployeeShift.Morning: return "Morning"; break; case EmployeeShift.Day: return "Day"; break; case EmployeeShift.Evening: return "Evenning"; break; case EmployeeShift.Night: return "Night"; break; default: return string.Empty; break; } }

//Using group By Clause on Linq //Grouping Employee based on their working shift
protected void btnGroupEmpbyShift_Click(object sender, EventArgs e) { CEmployeeDetails empd = new CEmployeeDetails(); Grid.DataSource = from emps in empd.Employees group emps by emps.Shift into aa select new { EmpShift = aa.Key, Employees = aa, }; }

//Simple Join using Linq //Employee Details class is joined with Employee PostClass
protected void btnJoinExample_Click(object sender, EventArgs e) { CEmployeeDetails empd = new CEmployeeDetails(); CEmployeePost empPo = new CEmployeePost(); Grid1.DataSource = from emps in empd.Employees join epo in empPo.EmpPostDetails on emps.EmpID equals epo.EmpID

57

BY: Sharad Pyakurel select new { emps.EmpID, emps.EmpName, emps.EmpAddress, emps.Salary, epo.PostName }; } } }

57

Das könnte Ihnen auch gefallen