Sunteți pe pagina 1din 33

C# Programming

Ketan Rajpal

Page: 1

1st Unit
The .NET Framework
The .NET Framework is a new and revolutionary platform created by Microsoft for developing applications. It is a
framework that runs primarily on Microsoft Windows Machine. It includes a large library and supports several
programming languages. .NET framework is a programming infrastructure created by Microsoft for building,
deploying, and running applications and services that use .NET technologies, such as desktop applications and Web
services. The different versions of .NET are: 1.0, 1.1, 2.0, 3.0, 3.5 and 4.0.
The features of .NET Framework
Interoperability: Computer systems commonly require interaction between new and older applications, the .NET
Framework provides means to access functionality that is implemented in programs that execute outside the .NET
environment.
Common Language Runtime Engine: The Common Language Runtime (CLR) is the execution engine of the .NET
Framework. All .NET programs execute under the supervision of the CLR, guaranteeing certain properties and
behaviors in the areas of memory management, security, and exception handling.
Language Independence: The .NET Framework introduces a Common Type System, Because of this feature; the .NET
Framework supports the exchange of types and object instances between libraries and applications written using
any conforming .NET language.
Base Class Library: The BCL provides classes which encapsulate a number of common functions, including file reading
and writing, graphic rendering, database interaction, XML document manipulation and so on.
Security: .NET provides a common security model for all applications.
Portability: The design of the .NET Framework is cross-platform compatible. A cross-platform application may run
on Microsoft Windows on the x86 architecture, Linux on the x86 architecture and Mac OS X on either
the PowerPC or x86 based Apple Macintosh systems. A cross-platform application may run on as many as all existing
platforms.
Motivation behind the .NET platform
Consistent Programming model and Multilanguage support: With .NET, for example, accessing data with a VB .NET
and a C# .NET looks very similar apart from slight syntactical differences. Both the programs need to import the
System.Data namespace, both the programs establish a connection with the database and both the programs run a
query and display the data on a data grid.
Direct Support for Security: With .NET, the Framework enables the developer and the system administrator to
specify method level security. This makes distributed computing more secure because .NET developers cooperate
with network security devices instead of working around their security limitations.
Simplified Development Efforts: ASP.NET and the .NET Framework simplify development by separating the
application logic and presentation logic making it easier to maintain the code. You write the design code
(presentation logic) and the actual code (application logic) separately eliminating the need to mix HTML code with
ASP code.
Easy Application Deployment and Maintenance: The .NET Framework makes it easy to deploy applications. In
the most common form, to install an application, all you need to do is copy the application along with the

C# Programming

Ketan Rajpal

Page: 2

components it requires into a directory on the target computer. The .NET Framework handles the details of
locating and loading the components an application needs, even if several versions of the same application exist on
the target computer. The .NET Framework ensures that all the components the application depends on are available
on the computer before the application begins to execute
Explain the architecture of .NET Framework.
Common language Infrastructure (CLI): The specification defines an environment that allows multiple high-level
languages to be used on different computer platforms without being rewritten for specific architectures. Common
Language Infrastructure specifies:
A common language (the Common Language Specification - CLS)
A common set of data types that any language must support (the Common Type System - CTS)
An introduction to the component structure
How the machine state is managed
How exceptions are handled
The CLI specification describes the following four aspects:
Common Type System (CTS): The common type system defines how types are declared, used, and managed
in the runtime, and is also an important part of the runtime's support for cross-language integration. The
common type system performs the following functions:

Establishes a framework that helps enable cross-language integration, type safety, and high performance
code execution.
Provides an object-oriented model that supports the complete implementation of many programming
languages.
Defines rules that languages must follow, which helps ensure that objects written in different languages
can interact with each other.

Metadata
Common Language Specification (CLS): It is a set of basic language features that .Net Languages needed to
develop Applications and Services, which are compatible with the .Net Framework. It ensures complete
interoperability among applications, regardless of the language used to create the application.
Virtual Execution System (VES): The VES loads and executes CLI-compatible programs, using the metadata to
combine separately generated pieces of code at runtime.
Common language Runtime (CLR): It is the run time environment that provides the underlying infrastructure
for Microsoft's .NET framework. This runtime is where the source code of an application is compiled into an
intermediate language called CIL (Common Intermediate Language), originally known as MSIL (Microsoft
Intermediate Language). When the program is then run, the CIL code is translated into the native code of the
operating system using a just-in-time (JIT) compiler. Some of the advantages of CLR are Security, Portability,
Flexibility, and Interoperability.
Assembly: In the .NET framework, an assembly is a compiled code library used for deployment, versioning, and
security. There are two types: process assemblies (EXE) and library assemblies (DLL). A process assembly represents
a process that will use classes defined in library assemblies. .NET assemblies contain code in CIL, which is usually
generated from a CLI language, and then compiled into machine language at run time by the CLR just-in-time
compiler. An assembly can consist of one or more files. Code files are called modules. An assembly can contain more
than one code module and since it is possible to use different languages to create code modules it is technically

C# Programming

Ketan Rajpal

Page: 3

possible to use several different languages to create an assembly. Visual Studio however does not support using
different languages in one assembly.
Scope of Assemblies: Assemblies can either contain a private or a public scope, based on the level of access required
by the clients who access it. The manifest contains information regarding the scope of an assembly.
Private Assembly: Assemblies are private in scope if only one application can access them. Private assemblies are
only available to clients in the same directory structure as the assembly.
Shared Assembly: When an assembly such as a system assembly contains features shared by various applications,
standard deployment techniques discourage the use of private assemblies. As a result, you need to maintain a copy
of the assembly for each client application. You can also register the assembly in the Global Assembly Cache (GAC),
so that all client applications refer to one copy of the assembly. This type of assembly is called a shared assembly.
Single File Assemblies: A single *.dll or *.exe file which contains the CIL code, type metadata, manifest and optional
resources in one binary package. Single file assemblies are by far and away the most common .NET binary. Visual
Studio can only create single file assemblies. Class Libraries, Windows Forms / WPF applications, Console
applications and Windows Services are all examples of single file assemblies.
Multi File Assemblies: A logical collection of files (termed modules) which are versioned and deployed
as a single logical unit. Multi-file assemblies can be useful when we wish to allow remote clients to download chunks
of an assembly on demand. The CLR will download requested modules to the local machine when requested.
Physically, multi-file assemblies consist of one file which contains the assembly manifest and additional modules
which contain CIL code and metadata descriptions for various types.
Metadata: .NET metadata, in the Microsoft .NET framework, refers to certain data structures embedded within
the Common Intermediate Language code that describes the high-level structure of the code. Metadata describes
all classes and class members that are defined in the assembly, and the classes and class members that the current
assembly will call from another assembly. The metadata for a method contains the complete description of the
method, including the class (and the assembly that contains the class), the return type and all of the
method parameters. A .NET language compiler will generate the metadata and store this in the assembly containing
the CIL. When the CLR executes CIL it will check to make sure that the metadata of the called method is the same as
the metadata that is stored in the calling method. This ensures that a method can only be called with exactly the
right number of parameters and exactly the right parameter types.
Namespaces: A namespace is a collection of different classes. All .NET applications are developed using classes from
the .NET System namespace. The namespace with all the built-in functionality is the System namespace. All other
namespaces are based on this System namespace. A namespace is just a grouping of related classes. It's a method of
putting classes inside a container so that they can be clearly distinguished from other classes with the same name.
Type Distinction: Namespace is a grouping of related types contained in an assembly. A single assembly can contain
any number of namespaces.
Platform Independent .NET: .NET is a collection of technologies. Some of these technologies are platform
independent, some are not. Some of these technologies are standards, some are not. The .NET development tools
create CIL. This is then compiled to native code on the target machine. It is possible to have the application compiled
when it is installed. Often the CIL will be compiled "Just In Time", JIT, the first time during a session when it is
required. .NET code will run on most of the common platforms you will encounter, including Mac, iPhone, Linux, etc.

C# Programming

Ketan Rajpal

Page: 4

Platforms like Windows will be able to run them exactly as if they were native applications. Platforms like iPhone
require that they go through a further compilation stage to create the native application before they are installed.
Mono .NET: Mono (a Spanish word for Monkey, as in 'code monkey') is an open source and commercially supported
distribution of .NET sponsored by Novell Corporation. Mono is targeted to run on many popular flavors of
Unix/Linux, Mac OS X, Solaris, and Windows.
Portable .NET: Portable .NET is distributed under the GNU General Public License. As the name implies, Portable
.NET intends to function on as many operating systems and architectures as possible, including many esoteric
platforms such as BeOS, AIX, Xbox, and Sony PlayStation 2 (no, I'm not kidding about those last two).
Managed Code: The role of the CLR doesnt end once you have compiled your code to MSIL, and a JIT compiler has
compiled that to native code. Code written using the .NET Framework is managed when it is executed. This means
that the CLR looks after your applications by managing memory, handling security, allowing cross-language
debugging, and so on. By contrast, applications that do not run under the control of the CLR are said to be
unmanaged, and certain languages such as C++ can be used to write such applications, which, for example, access
low-level functions of the operating system. However, in C# you can write only code that runs in a managed
environment. You will make use of the managed features of the CLR and allow .NET itself to handle any interaction
with the operating system.
Boxing: Converting value types to reference types is also known as boxing. As can be seen in the example below, it is
not necessary to tell the compiler an Int32 is boxed to an object, because it takes care of this itself.
Example of Implicit Boxing
Int32 x = 10;
object o = x ; // Implicit boxing
Console.WriteLine("The Object o = {0}",o); // prints out 10

Example of Explicit Boxing


Int32 x = 10;
object o = (object) x; // Explicit boxing
Console.WriteLine("The object o = {0}",o); // prints out 10

Un-Boxing: The following example intends to show how to unbox a reference type back to a value type. First an
Int32 is boxed to an object, and then it is unboxed again. Note that unboxing requires explicit cast.
Example of Un-Boxing
Int32 x = 5;
object o1 = x; // Implicit Boxing
x = (int)o1; // Explicit Unboxing

C# Programming

Ketan Rajpal

Page: 5

2nd Unit
C# pronounced See Sharp is a multi-paradigm programming language encompassing imperative, declarative,
functional, generic, object-oriented and component-oriented programming disciplines. C# is intended to be a simple,
modern, general-purpose, object-oriented programming language. As C# is a development language of .NET
framework, its evolution is closely related with that .NET framework runtime and Visual Studio development
environment. C# is intended to be a simple, modern, general-purpose, object-oriented programming language.
C# Design Goals: The ECMA standard lists these design goals for C#
C# language is intended to be a simple, modern, general-purpose, object-oriented programming language.
The language, and implementations thereof, should provide support for software engineering principles such
as strong type checking, array bounds checking, detection of attempts to use uninitialized variables,
and automatic garbage collection. Software robustness, durability, and programmer productivity are
important.
The language is intended for use in developing software components suitable for deployment in distributed
environments.
Source code portability is very important, as is programmer portability, especially for those programmers
already familiar with C and C++.
Support for internationalization is very important.
C# is intended to be suitable for writing applications for both hosted and embedded systems, ranging from
the very large that use sophisticated operating systems, down to the very small having dedicated functions.
Although C# applications are intended to be economical with regard to memory and processing
power requirements, the language was not intended to compete directly on performance and size with C,
C++ or assembly language.
My First C# Program
namespace FirstProgram {
using System;
class Example {
static void Main ( ) {
Console.WriteLine ("Hello world!");
}
}
}

Reference and Value Types: C# has a unified type system. This unified type system is called Common Type System.
CTS separate data types into two categories:
Value Types: A value type contains the actual value. When a value type is assigned to another value type, it is
copied. In simple words, all value based types are allocated on the stack. By saying stack, we mean things are kept
one on top of the other. We keep track of each value at the top.
Example of Value Type
using System;
class Test {
static void Main ( ) {
int x = 3;
int y = x; // assign x to y, y is now a copy of x
x++; // increment x to 4
Console.WriteLine (y); // prints 3
}}

C# Programming

Ketan Rajpal

Page: 6

Reference Types: A reference type contains a reference to the value. When a reference type is assigned to another
reference type, a reference is assigned to the value. All reference based types are allocated on the heap. By saying
heap, we mean things are kept in a mashed order. We keep track of each value by its address that is referenced by a
pointer to it.
Example of Reference Type
using System.Text;
class Test {
static void Main ( ) {
StringBuilder x = new StringBuilder ("hello");
StringBuilder y = x;
x.Append (" there");
Console.WriteLine (y); // prints "hello there"
}
}

All value types are implicitly derived from System.ValueType. This class actually overrides the implementation in
System.Object, the base class for all objects which is a Reference Type itself. Data types like integers, floating point
numbers, character data, Boolean values, Enumerations and Structures are examples of Value Types. Classes,
Strings, Arrays are examples of Reference Types. A Value Type may not contain NULL values. Reference Types may
contain NULL values. It is not possible to derive new types from Value Types. This is possible in Reference types.
However, Value Types like Structures can implement interfaces.
Value types
Integer, signed (sbyte, short, int, long)
Integer, unsigned (byte, ushort, uint, ulong)
Floating-point (float, decimal, double)
Reference types
Object
String
Primitive types: Any data types directly supported by the compiler are called primitive types. A primitive Type is not
the same then a Value Type. A basic type is a data type provided by a programming language as a basic building
block. Most languages allow more complicated composite types to be recursively constructed starting from basic
types. A built-in type is a data type for which the programming language provides built-in support.
Null able Types: The term null is an interesting programming concept in that it does not mean the same as zero or
blank; rather, it often implies missing or otherwise undefined data and because of this, is frequently used as a flag in
this scenario. Null ability refers to the ability of a data type to accept and appropriately handle NULL values.
Example of Null able Types
class NullableExample
{
static void Main()
{
int? num = null;
if (num.HasValue == true)
{
System.Console.WriteLine("num = " + num.Value);
}

C# Programming

Ketan Rajpal

Page: 7

else
{
System.Console.WriteLine("num = Null");
}
// y is set to zero
int y = num.GetValueOrDefault();
// num.Value throws an InvalidOperationException if num.HasValue is false
try
{
y = num.Value;
}
catch (System.InvalidOperationException e)
{
System.Console.WriteLine(e.Message);
}
}
}

The example will display the output:


num = Null

Enumerable Types: An enumeration type (also named an enumeration or an enum) provides an efficient way to
define a set of named integral constants that may be assigned to a variable.
enum Days { Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday };
enum Months : byte { Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec };

For example, assume that you have to define a variable whose value will represent a day of the week. There are only
seven meaningful values which that variable will ever store. To define those values, you can use an enumeration
type, which is declared by using the enum keyword.
Arrays: Arrays allow a group of elements of a particular type to be stored in a contiguous block of memory. An array
is specified by placing square brackets after the element type.
Single Dimensional Array:
Example of Single Dimensional Array
char[ ] vowels = new char[ ] {'a','e','i','o','u'};
Console.WriteLine(vowels [1]); // Prints "e"

Multi Dimensional Array: Multidimensional arrays come in two varieties: rectangular and jagged. Rectangular arrays
represent an n-dimensional block, while jagged arrays are arrays of arrays.
Example of Multi Dimensional array
// rectangular
int [,,] matrixR = new int [3, 4, 5]; // creates 1 big cube
// jagged
int [ ][ ][ ] matrixJ = new int [3][ ][ ];
for (int i = 0; i < 3; i++) {
matrixJ[i] = new int [4][ ];
for (int j = 0; j < 4; j++)
matrixJ[i][j] = new int [5];

C# Programming

Ketan Rajpal

Page: 8

}
// assign an element
matrixR [1,1,1] = matrixJ [1][1][1] = 7;

Classes: A class is a construct that enables you to create your own custom types by grouping together variables of
other types, methods and events. A class is like a blueprint. It defines the data and behavior of a type. A class usually
represents a noun, such as a person, place or thing. For example, "Banana" is an instance of the class "Fruit" (a
"Fruit" object). It is of the type "Fruit". In object-oriented terms, we say that your bicycle is an instance of the class
of objects known as bicycles. A class is the blueprint from which individual objects are created. A class can have
subclasses that can inherit all or some of the characteristics of the class. In relation to each subclass, the class
becomes the super class. Subclasses can also define their own methods and variables that are not part of their super
class. The structure of a class and its subclasses is called the class hierarchy.
Objects: An object is any entity that can be manipulated by the commands of a programming language, such as
a value, variable, function, or data structure. An object is an instance of a class.
Example of Classes and Objects
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
public Person(string name, int age)
{
Name = name;
Age = age;
}
}
class Program
{
static void Main()
{
Person person1 = new Person("Leopold", 6);
Console.WriteLine("person1 Name = {0} Age = {1}", person1.Name, person1.Age);
Person person2 = person1;
person2.Name = "Molly";
person2.Age = 16;
Console.WriteLine("person2 Name = {0} Age = {1}", person2.Name, person2.Age);
Console.WriteLine("person1 Name = {0} Age = {1}", person1.Name, person1.Age);
Console.WriteLine("Press any key to exit.");
Console.ReadKey();
}
}

The example will display the output:


person1 Name = Leopold Age = 6
person2 Name = Molly Age = 16
person1 Name = Molly Age = 16

The This Keyword: The this keyword denotes a variable that is a reference to a class or struct instance and is only
accessible from within no static function members of the class or struct. The this keyword is also used by a
constructor to call an overloaded constructor or declare or access indexers. A common use of the this variable is to
distinguish a field name from a parameter name.

C# Programming

Ketan Rajpal

Page: 9

Example of This Keyword


class Dude {
string name;
public Dude (string name) {
this.name = name;
}
public void Introduce(Dude a) {
if (a!=this)
Console.WriteLine("Hello, I'm "+name);
}
}

Static Classes and Static Class Members: Static classes and class members are used to create data and functions that
can be accessed without creating an instance of the class. Static class members can be used to separate data and
behavior that is independent of any object identity: the data and functions do not change regardless of what
happens to the object. Static classes can be used when there is no data or behavior in the class that depends on
object identity. A class can be declared static, indicating that it contains only static members. It is not possible to
create instances of a static class using the new keyword. Static classes are loaded automatically by the .NET
Framework common language runtime (CLR) when the program or namespace containing the class is loaded. The
main features of a static class are:
They only contain static members.
They cannot be instantiated.
They are sealed.
They cannot contain Instance Constructors (C# Programming Guide).
Example of Static Classes and Static Class Members
public static class TemperatureConverter
{
public static double CelsiusToFahrenheit(string temperatureCelsius)
{
double celsius = System.Double.Parse(temperatureCelsius);
double fahrenheit = (celsius * 9 / 5) + 32;
return fahrenheit;
}
public static double FahrenheitToCelsius(string temperatureFahrenheit)
{
double fahrenheit = System.Double.Parse(temperatureFahrenheit);
double celsius = (fahrenheit - 32) * 5 / 9;
return celsius;
}
}
class TestTemperatureConverter
{
static void Main()
{
System.Console.WriteLine("Please select the convertor direction");
System.Console.WriteLine("1. From Celsius to Fahrenheit.");
System.Console.WriteLine("2. From Fahrenheit to Celsius.");
System.Console.Write(":");
string selection = System.Console.ReadLine();
double F, C = 0;

C# Programming

Ketan Rajpal

Page: 10

switch (selection)
{
case "1":
System.Console.Write("Please enter the Celsius temperature: ");
F
TemperatureConverter.CelsiusToFahrenheit(System.Console.ReadLine());
System.Console.WriteLine("Temperature in Fahrenheit: {0:F2}", F);
break;
case "2":
System.Console.Write("Please enter the Fahrenheit temperature: ");
C
TemperatureConverter.FahrenheitToCelsius(System.Console.ReadLine());
System.Console.WriteLine("Temperature in Celsius: {0:F2}", C);
break;

default:
System.Console.WriteLine("Please select a convertor.");
break;
}
}
}

The example will display the output:


Please select the convertor
1. From Celsius to Fahrenheit.
2. From Fahrenheit to Celsius.
:2
Please enter the Fahrenheit temperature: 98.6
Temperature in Celsius: 37.00
Additional sample output might look as follows:
Please select the convertor
1. From Celsius to Fahrenheit.
2. From Fahrenheit to Celsius.
:1
Please enter the Celsius temperature: 37.00
Temperature in Fahrenheit: 98.60

Garbage Collector: In C and C++, many objects require the programmer to allocate their resources once declared,
before the objects can be safely used. Releasing these resources back to the free memory pool once the object has
been used is also the responsibility of the programmer. If resources are not released, the code is said to leak
memory, as more and more resources are consumed needlessly. On the other hand, if resources are released
prematurely, loss of data, the corruption of other memory areas, and null pointer exceptions can occur. C# prevent
these dangers by independently managing the lifetime of all objects in use by an application. In C#, garbage
collection is handled by the common language runtime (CLR) with similar functionality to that of the JVM. The CLR
garbage collector periodically checks the memory heap for any unreferenced objects, and releases the resources
held by these objects. In C# we have Automatic Memory Management.
Method Overloading: Method overloading allows the programmer to define many methods with the same name but
with a different set of parameters. Each combination of parameter types is known as a signature of the method.
When a call is made to one of these overloaded methods, the compiler automatically determines which of the
methods should be used according to the arguments used in the call and the available method signatures.

C# Programming

Ketan Rajpal

Page: 11

Constructors: Whenever a class or struct is created, its constructor is called. A class or struct may have multiple
constructors that take different arguments. Constructors enable the programmer to set default values, limit
instantiation, and write code that is flexible and easy to read. Constructors are class methods that are executed
when an object of a given type is created. Constructors have the same name as the class, and usually initialize the
data members of the new object.
A constructor that takes no parameters is called a default constructor. Default constructors are invoked whenever
an object is instantiated by using the new operator and no arguments are provided to new.
Unless the class is static, classes without constructors are given a public default constructor by the C# compiler in
order to enable class instantiation.
Both classes and structs can define constructors that take parameters. (Parameterized Constructors) Constructors
that take parameters must be called through a new statement or a base statement. Classes and structs can also
define multiple constructors, and neither is required to define a default constructor.
Constructors can be marked as public, private, protected, internal, or protected internal. These access modifiers
define how users of the class can construct the class. A constructor can be declared static by using
the static keyword. Static constructors are called automatically, immediately before any static fields are accessed,
and are generally used to initialize static class members.
C# does not provide a copy constructor. If you create a new object and want to copy the values from an existing
object, you have to write the appropriate method yourself.
Instance constructors are used to create and initialize any instance member variables when you use
the new expression to create an object of a class. To initialize a static class, or static variables in a non-static class,
you must define a static constructor.
Example of Instance Constructors
class CoOrds
{
public int x, y;
public CoOrds()
{
x = 0;
y = 0;
}
public CoOrds(int x, int y)
{
this.x = x;
this.y = y;
}
public override string ToString()
{
return (String.Format("({0},{1})", x, y));
}
}
class MainClass
{
static void Main()
{
CoOrds p1 = new CoOrds();
CoOrds p2 = new CoOrds(5, 3);

C# Programming

Ketan Rajpal

Page: 12

Console.WriteLine("CoOrds #1 at {0}", p1);


Console.WriteLine("CoOrds #2 at {0}", p2);
Console.ReadKey();
}
}

The example will display the output:


CoOrds #1 at (0,0)
CoOrds #2 at (5,3)

Encapsulating Data: Encapsulation is the procedure of covering up of data and functions into a single unit (called
class). An encapsulated object is often called an abstract data type. The need of encapsulation is to protect or
prevent the code (data) from accidental corruption due to the silly little errors that we are all prone to make.
Properties are named members of classes, structs, and interfaces. They provide a flexible mechanism to read, write,
or compute the values of private fields through accessors. Properties are a new language feature introduced with C#.
Only a few languages support this property. Properties in C# helps in protect a field in a class by reading and writing
to it. The first method itself is good but Encapsulation can be accomplished much smoother with properties. The
accessor of a property contains the executable statements associated with getting (reading or computing) or setting
(writing) the property. The accessor declarations can contain a get accessor, a set accessor, or both. The declarations
take the following forms: set {accessor-body}, get {accessor-body}. accessor-body: The block that contains the
statements to be executed when the accessor is invoked.
Example of Encapsulating Data (Property)
using system;
public class Department
{
private string departname;
public string Departname
{
get
{
return departname;
}
set
{
departname=value;
}
}
}
public class Departmentmain
{
public static int Main(string[] args)
{
Department d= new Department();
d.departname="Communication";
Console.WriteLine("The Department is :{0}",d.Departname);
return 0;
}
}

Access Modifiers: All types and type members have an accessibility level, which controls whether they can be used
from other code in your assembly or other assemblies. You can use the following access modifiers to specify the
accessibility of a type or member when you declare it:

C# Programming

Ketan Rajpal

Page: 13

Public: The type or member can be accessed by any other code in the same assembly or another assembly
that references it.
Private: The type or member can be accessed only by code in the same class or struct.
Protected: The type or member can be accessed only by code in the same class or struct, or in a class that is
derived from that class.
Internal: The type or member can be accessed by any code in the same assembly, but not from another
assembly.
Protected Internal: The type or member can be accessed by any code in the assembly in which it is declared,
or from within a derived class in another assembly. Access from another assembly must take place within a
class declaration that derives from the class in which the protected internal element is declared, and it must
take place through an instance of the derived class type.

Syntax of Access Modifiers


public class Tricycle
{
// protected method:
protected void Pedal() { }
// private field:
private int wheels = 3;
// protected internal property:
protected internal int Wheels
{
get { return wheels; }
}
}

Indexers Arrays: Indexers permit instances of a class or struct to be indexed in the same way as arrays. Indexers are
similar to properties except that their accessors take parameters.
Example of Indexers Arrays
using System;
class IndexerClass
{
private int [] myArray = new int[100];
public int this [int index]
// Indexer declaration
{
get
{
// Check the index limits.
if (index < 0 || index >= 100)
return 0;
else
return myArray[index];
}
set
{
if (!(index < 0 || index >= 100))
myArray[index] = value;
}
}
}

C# Programming

Ketan Rajpal

Page: 14

public class MainClass


{
public static void Main()
{
IndexerClass b = new IndexerClass();
// Call the indexer to initialize the elements #3 and #5.
b[3] = 256;
b[5] = 1024;
for (int i=0; i<=10; i++)
{
Console.WriteLine("Element #{0} = {1}", i, b[i]);
}
}
}

The example will display the output:


Element
Element
Element
Element
Element
Element
Element
Element
Element
Element
Element

#0 = 0
#1 = 0
#2 = 0
#3 = 256
#4 = 0
#5 = 1024
#6 = 0
#7 = 0
#8 = 0
#9 = 0
#10 = 0

Property and Indexers (Difference)


Property

Indexer

Identified by its name.

Identified by its signature.

Accessed through a simple name or a member


access.

Accessed through an element access.

Can be a static or an instance member.

Must be an instance member.

A get accessor of a property has no parameters.

A get accessor of an indexer has the same formal


parameter list as the indexer.

A set accessor of a property


implicit value parameter.

contains

the

A set accessor of an indexer has the same formal


parameter list as the indexer, in addition to the value
parameter.

Readonly Field: The readonly keyword is a modifier that you can use on fields. When a field declaration includes
a readonly modifier, assignments to the fields introduced by the declaration can only occur as part of the declaration
or in a constructor in the same class.
public readonly int y = 5;

The readonly keyword is different from the const keyword. A const field can only be initialized at the declaration of
the field. A readonly field can be initialized either at the declaration or in a constructor. Therefore, readonly fields
can have different values depending on the constructor used. Also, while a const field is a compile-time constant,
the readonly field can be used for runtime constants.

C# Programming

Ketan Rajpal

Page: 15

Structures (Struct): A struct is similar to a class. Both classes and structs can implement interfaces.
Structure and Class (Difference)
Structure
A struct is a value type

Class
A class is a reference type

A struct can inherit only from an object and is


implicitly sealed

A class fully supports inheritance.

A structure cannot have a destructor

A class can have a destructor

The default parameter less constructor for a struct


initializes each field with a default value. If a struct
declares a constructor, then all of its fields must be
assigned in that constructor call.

A class can define a custom parameter less constructor


and initialize instance fields.

Interfaces: An interface is similar to a class, but with the following major differences
An interface provides a specification rather than an implementation for its members. This is similar to a pure
abstract class, which is an abstract class consisting of only abstract members.
A class and struct can implement multiple interfaces, while a class can inherit only from a single class.
A struct can implement an interface, but a struct cannot inherit from a class.
An interface is comprised of Method, Property, Indexer, and Event.
Example of Interface
using System;
interface IPoint
{
int x
{
get;
set;
}
int y
{
get;
set;
}
}
class Point : IPoint
{
private int _x;
private int _y;
public Point(int x, int y)
{
_x = x;
_y = y;
}
public int x
{
get
{

C# Programming

Ketan Rajpal

Page: 16

return _x;
}
set
{
_x = value;
}
}
public int y
{
get
{
return _y;
}
set
{
_y = value;
}
}
}
class MainClass
{
static void PrintPoint(IPoint p)
{
Console.WriteLine("x={0}, y={1}", p.x, p.y);
}
static void Main()
{
Point p = new Point(2, 3);
Console.Write("My Point: ");
PrintPoint(p);
}
}

The example will display the output:


My Point: x=2, y=3

Nested Classes: A nested type is declared within the scope of another type. A nested type can access all the
members of its enclosing type, regardless of a member's access modifier. A nested type can be hidden from other
types with type-member access modifiers. Accessing a nested type from outside of its enclosing type requires
specifying the type name. This is the same principle used for static members.
Example of Nested Classes
using System;
public class Container
{
public class Nested
{
private Container parent;
public Nested()
{
}

C# Programming

Ketan Rajpal

Page: 17

public Nested(Container parent)


{
this.parent = parent;
}
}
}
Container.Nested nest = new Container.Nested();

Abstract and Sealed Class: The abstract keyword enables you to create classes and class members that are
incomplete and must be implemented in a derived class. The sealed keyword enables you to prevent the inheritance
of a class or certain class members that were previously marked virtual. An abstract class cannot be instantiated. The
purpose of an abstract class is to provide a common definition of a base class that multiple derived classes can share.
Abstract classes may also define abstract methods. This is accomplished by adding the keyword abstract before the
return type of the method.
Example of Abstract Class
public class D
{
public virtual void DoWork(int i)
{
// Original implementation.
}
}
public abstract class E : D
{
public abstract override void DoWork(int i);
}
public class F : E
{
public override void DoWork(int i)
{
// New implementation.
}
}

Example of Sealed Class


public class D : C
{
public sealed override void DoWork() { }
}

String Class: The string type represents a sequence of zero or more Unicode characters. String is an alias for String in
the .NET Framework. Strings have comparison, appending, inserting, and conversion, copying, formatting, indexing,
joining, splitting, padding, trimming, removing, replacing, and searching methods.
Comparing Strings: The = = operator is overloaded, so you can easily compare two strings by value.
string a = "abracadabra";
string b = "abracadabra";
Console.WriteLine(a= =b); // Prints "True"

Immutability of Strings: Strings are immutable, which means they can't be modified after creation.
Consequently, many of the methods that initially appear to modify a string actually create a new string.
string a = "Heat";

C# Programming

Ketan Rajpal

Page: 18

string b = a.Insert(3, "r")


Console.WriteLine(b); // Prints Heart

Formatting Strings: The Format( ) method provides a convenient way to build strings that make use of
embedded parameters. Parameters in such strings can be of any type, including both predefined and userdefined types.
using System;
class TestFormatting {
static void Main( ) {
int i = 2;
decimal m = 42.73m;
string s = String.Format("Account {0} has {1:C}.", i, m);
Console.WriteLine(s); // Prints "Account 2 has $42.73"
}
}

String Builder Class: Represents a mutable string of characters. This class cannot be inherited.
Capacity: Gets or sets the maximum number of characters that can be contained in the memory allocated by
the current instance.
Chars: Gets or sets the character at the specified character position in this instance.
Length: Gets or sets the length of this instance.
MaxCapacity: Gets the maximum capacity of this instance.
Append: Overloaded. Appends the string representation of a specified object to the end of this instance.
AppendFormat: Overloaded. Appends a formatted string, which contains zero or more format specifications,
to this instance. Each format specification is replaced by the string representation of a corresponding object
argument.
EnsureCapacity: Ensures that the capacity of this instance of StringBuilder is at least the specified value.
Equals: Overloaded. Returns a value indicating whether this instance is equal to a specified object.
GetType: Gets the Type of the current instance.
Insert: Overloaded. Inserts the string representation of a specified object into this instance at a specified
character position.
Remove: Removes the specified range of characters from this instance.
Replace: Overloaded. Replaces all occurrences of a specified character or string in this instance with another
specified character or string.
ToString: Overloaded. Overridden. Converts a StringBuilder to a String.
Handling Errors: An exceptional condition is an error situation that occurs during the normal flow of program and
prevents the program from continuing correctly. C# provides exception handling mechanism for handling errors and
conditions such as division of numbers by Zero (0) is difficult to predict however, that can be handled by using
exceptions. The C# language's exception handling features help you deal with any unexpected or exceptional
situations that occur when a program is running.
A try block is used by C# programmers to partition code that might be affected by an exception.
Associated catch blocks are used to handle any resulting exceptions. A finally block contains code that is run
regardless of whether or not an exception is thrown in the try block, such as releasing resources that are allocated in
the try block. A try block requires one or more associated catch blocks, or a finally block, or both.
Syntax of Exception Handling
try
{
// Code to try goes here.
}

C# Programming

Ketan Rajpal

Page: 19

catch (SomeSpecificException ex)


{
// Code to handle the exception goes here.
// Only catch exceptions that you know how to handle.
// Never catch base class System.Exception without
// rethrowing it at the end of the catch block.
}
finally
{
// Code to execute after the try (and possibly catch) blocks
// goes here.
}

Example of Exception Handling


class ExceptionTest
{
static double SafeDivision(double x, double y)
{
if (y == 0)
throw new System.DivideByZeroException();
return x / y;
}
static void Main()
{
// Input for test purposes. Change the values to see
// exception handling behavior.
double a = 98, b = 0;
double result = 0;
try
{
result = SafeDivision(a, b);
Console.WriteLine("{0} divided by {1} = {2}", a, b, result);
}
catch (DivideByZeroException e)
{
Console.WriteLine("Attempted divide by zero.");
}
}
}

Compiler Generated Exceptions: Some exceptions are thrown automatically by the .NET Framework's common
language runtime (CLR) when basic operations fail.
ArithmeticException: A base class for exceptions that occur during arithmetic operations, such as
DivideByZeroException and OverflowException.
ArrayTypeMismatchException: Thrown when an array cannot store a given element because the actual type
of the element is incompatible with the actual type of the array.
DivideByZeroException: Thrown when an attempt is made to divide an integral value by zero.
IndexOutOfRangeException: Thrown when an attempt is made to index an array when the index is less than
zero or outside the bounds of the array.
InvalidCastException: Thrown when an explicit conversion from a base type to an interface or to a derived
type fails at runtime.
NullReferenceException: Thrown when you attempt to reference an object whose value is null.
OutOfMemoryException: Thrown when an attempt to allocate memory using the new operator fails. This
indicates that the memory available to the common language runtime has been exhausted.

C# Programming

Ketan Rajpal

Page: 20

OverflowException: Thrown when an arithmetic operation in a checked context overflows.


StackOverflowException: Thrown when the execution stack is exhausted by having too many pending
method calls; usually indicates a very deep or infinite recursion.
TypeInitializationException: Thrown when a static constructor throws an exception and no compatible catch
clause exists to catch it.
The root of all Classes- Object: All C# classes, of any type, ultimately derive from a single class: Object. Object is the
base class for all other classes. A base class is the immediate parent of a derived class. A derived class can be the
base to further derived classes, creating an inheritance tree or hierarchy. A root class is the topmost class in an
inheritance hierarchy. In C#, the root class is Object.
Equals: Evaluates whether two objects are equivalent
GetHashCode: Allows objects to provide their own hash function for use in collections
GetType: Provides access to the Type object
ToString: Provides a string representation of the object
Finalize: Cleans up non memory resources; implemented by a destructor.
Specialization and Generalization: One of the most important relationships among objects in the real world is
specialization, which can be described as the is-a relationship. Generalization is the process of extracting shared
characteristics from two or more classes, and combining them into a generalized superclass. Shared characteristics
can be attributes, associations, or methods.
Inheritance: Mechanism of deriving a new class from an old is known as inheritance. The old class refers to as base
class and new one is called the derived or sub class. A class can inherit from another class to extend or customize the
original class. Inheriting from a class allows you to reuse the functionality in that class instead of building it from
scratch.
Syntax to inherit from a class
Public class derivedclass:baseclass

Program of Inheritance and Polymorphism


public class Shape
{
public int X { get; private set; }
public int Y { get; private set; }
public int Height { get; set; }
public int Width { get; set; }
public virtual void Draw()
{
Console.WriteLine("Performing base class drawing tasks");
}
}
class Circle : Shape
{
public override void Draw()
{
Console.WriteLine("Drawing a circle");
base.Draw();
}
}
class Rectangle : Shape

C# Programming

Page: 21

Ketan Rajpal

{
public override void Draw()
{
Console.WriteLine("Drawing a rectangle");
base.Draw();
}
}
class Triangle : Shape
{
public override void Draw()
{
Console.WriteLine("Drawing a triangle");
base.Draw();
}
}
class Program
{
static void Main(string[] args)
{
System.Collections.Generic.List<Shape>
System.Collections.Generic.List<Shape>();
shapes.Add(new Rectangle());
shapes.Add(new Triangle());
shapes.Add(new Circle());
foreach (Shape s in shapes)
{
s.Draw();
}
Console.WriteLine("Press any key to exit.");
Console.ReadKey();
}

shapes

new

The example will display the output:


Drawing a rectangle
Performing base class drawing tasks
Drawing a triangle
Performing base class drawing tasks
Drawing a circle
Performing base class drawing tasks

The DateTime class: The System.DateTime class of the .NET Framework allows you to use, store, and manipulate
data of time and date. It has methods for manipulating date such as adding or subtracting days, months, or years to
the current date and then returning the resulting date. It has some methods to show your date in various formats.
Program of DateTime Class
public class Program
{
public static void Main()
{
DateTime newyear = new DateTime(2010, 12, 25);
Console.WriteLine(newyear.ToString());
}

C# Programming

Ketan Rajpal

Page: 22

The example will display the output: 12/25/2010 12:00:00 AM


We used the constructor which accepts the year, the month, and the date to initialize our DateTime object. We used
the ToString () method of the DateTime class to display the date and time. The default ToString() method displays
your DateTime object in this format: MM/DD/YYYY HH:MM:SS AM/PM.
Constructors present in DateTime Class

DateTime()
DateTime(int year, int month, int day)
DateTime(int year, int month, int day, int hour, int minute, int second)
DateTime(int year, int month, int day, int hour,
int minute, int second, int millisecond)

Using the default parameterless constructor initializes the date to 01/01/0001 12:00:00 AM. To obtain the current
date and time, you can use the Now static property of the DateTime class.
Predefined Methods
DateTime now = DateTime.Now;
DateTime today = DateTime.Today;

Program of DateTime Class


public class Program
{
public static void Main()
{
DateTime myDate = DateTime.Now;
Console.WriteLine("Year: " + myDate.Year);
Console.WriteLine("Month: " + myDate.Month);
Console.WriteLine("Day: " + myDate.Day);
Console.WriteLine("Today is {0}.", myDate.DayOfWeek.ToString());
//Assign newDate with the current date added by 3 days
DateTime newDate = myDate.AddDays(3);
Console.WriteLine("The date 3 days from now is {0}.",
newDate.ToShortDateString());
//Assign newdate with the current date subtracted by 3 days
newDate = myDate.AddDays(-3);
Console.WriteLine("The date 3 days ago is {0}.", newDate.ToShortDateString());
}
}

The example will display the output:


Year: 2010
Month: 10
Day: 3
Today is Sunday.
The date 3 days from now is 10/6/2010.
The date 3 days ago is 9/30/2010.

C# Programming

Ketan Rajpal

Page: 23

3rd Unit
Delegate and event: An event is a message sent by an object to signal the occurrence of an action. The object that
raises (triggers) the event is called the event sender. The object that captures the event and responds to it is called
the event receiver. In event communication, the event sender class does not know which object or method will
receive (handle) the events it raises. What is needed is an intermediary (or pointer-like mechanism) between the
source and the receiver. The .NET Framework defines a special type (Delegate) that provides the functionality of a
function pointer. A delegate is a class that can hold a reference to a method. Unlike other classes, a delegate class
has a signature, and it can hold references only to methods that match its signature. A delegate is thus equivalent to
a type-safe function pointer or a callback. While delegates have other uses, the discussion here focuses on the event
handling functionality of delegates. The following example shows an event delegate declaration.
public delegate void AlarmEventHandler(object sender, AlarmEventArgs e);

The syntax is similar to that of a method declaration; however, the delegate keyword informs the compiler that
AlarmEventHandler is a delegate type.
Anonymous Delegates: Anonymous Method declarations consist of the keyword delegate, an optional parameter
list and a statement list enclosed in parenthesis.
btnSave.Click += delegate { SaveChanges(); lblStatus.Text = "Your changes have been
saved"; };

Event Handler using Anonymous Methods, with a parameter list


btnSave.Click += delegate(object sender, EventArgs e)
{
MessageBox.Show(((Button)sender).Text);
SaveChanges();
MessageBox.Show("Your changes have been saved");
}

Anonymous methods can be specified with parameters enclosed in parenthesis, or without parameters, with empty
parenthesis. When parameters are specified, the signature of the anonymous method must match the signature of
the delegate. When the delegate has no parameters, empty parenthesis are specified in the anonymous method
declaration. When an anonymous method is declared without parenthesis, it can be assigned to a delegate with any
signature.
Note that method attributes cannot be applied to Anonymous methods. Also, anonymous methods can be added to
the invocation list for delegates but can be deleted from the invocation list only if they have been saved to
delegates.
An advantage offered with the use of anonymous methods is that they allow access to the local state of the
containing function member.
FUNC: The Func type is a parameterized type and you must specify the number and kinds of parameters, and also
the type of the return value. The Func type provides a way to store anonymous methods in a generalized and simple
way.
Example of FUNC
class Program
{
static void Main()
{
Func<int, string> func1 = (x) => string.Format("string = {0}", x);
Func<bool, int, string> func2 = (b, x) =>string.Format("string = {0} and {1}", b,
x);
Func<double> func3 = () => Math.PI / 2;
Console.WriteLine(func1.Invoke(5));
Console.WriteLine(func2.Invoke(true, 10));

C# Programming

Ketan Rajpal

Console.WriteLine(func3.Invoke());
}

The example will display the output:


string = 5
string = True and 10
1.5707963267949

Action Delegates: Encapsulates a method that has no parameters and does not return a value.
Syntax: public delegate void Action()
Example of Action Delegates
using System;
using System.Windows.Forms;
public class Name
{
private string instanceName;
public Name(string name)
{
this.instanceName = name;
}
public void DisplayToConsole()
{
Console.WriteLine(this.instanceName);
}
public void DisplayToWindow()
{
MessageBox.Show(this.instanceName);
}
}
public class LambdaExpression
{
public static void Main()
{
Name testName = new Name("Koani");
Action showMethod = () => testName.DisplayToWindow();
showMethod();
}
}

Action Delegates: Encapsulates a method that has a single parameter and does not return a value.
Syntax: public delegate void Action<in T>(T obj)
Example of Action Delegates
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
List<String> names = new List<String>();
names.Add("Bruce");
names.Add("Alfred");
names.Add("Tim");
names.Add("Richard");
names.ForEach(Print);
names.ForEach(delegate(String name)
{
Console.WriteLine(name);

Page: 24

C# Programming

Ketan Rajpal

Page: 25

});
}

private static void Print(string s)


{
Console.WriteLine(s);
}

The example will display the output:


Bruce
Alfred
Tim
Richard
Bruce
Alfred
Tim
Richard

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.
Example of Generics
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();

Explicit Interfaces Implementation: If a class implements two interfaces that contain a member with the same
signature, then implementing that member on the class will cause both interfaces to use that member as their
implementation. If the two interface members do not perform the same function, however, this can lead to an
incorrect implementation of one or both of the interfaces. It is possible to implement an interface member
explicitlycreating a class member that is only called through the interface, and is specific to that interface. This is
accomplished by naming the class member with the name of the interface and a period.
Example of Explicit Interfaces Implementation
interface IControl
{
void Paint();
}
interface ISurface
{
void Paint();
}
public class SampleClass : IControl, ISurface
{
void IControl.Paint()
{
System.Console.WriteLine("IControl.Paint");
}
void ISurface.Paint()
{
System.Console.WriteLine("ISurface.Paint");
}

C# Programming

Ketan Rajpal

Page: 26

}
SampleClass obj = new SampleClass();
//obj.Paint(); // Compiler error.
IControl c = (IControl)obj;
c.Paint(); // Calls IControl.Paint on SampleClass.
ISurface s = (ISurface)obj;
s.Paint(); // Calls ISurface.Paint on SampleClass.

Collection Class: The .NET Framework provides specialized classes for data storage and retrieval. These classes
provide support for stacks, queues, lists, and hash tables. Most collection classes implement the same interfaces,
and these interfaces may be inherited to create new collection classes that fit more specialized data storage needs.
Collection Classes have the following properties
Collection classes are defined as part of the System.Collections or System.Collections.Generic namespace.
Most collection classes derive from the interfaces ICollection, IComparer, IEnumerable, IList, IDictionary,
and IDictionaryEnumerator and their generic equivalents.
Using generic collection classes provides increased type-safety and in some cases can provide better
performance, especially when storing value types.
The following generic types correspond to existing collection types:
List is the generic class corresponding to ArrayList.
Dictionary is the generic class corresponding to Hashtable.
Collection is the generic class corresponding to CollectionBase. Collection can be used as a base class, but
unlike CollectionBase it is not abstract, making it much easier to use.
ReadOnlyCollection is the generic class corresponding to ReadOnlyCollectionBase. ReadOnlyCollection is not
abstract, and has a constructor that makes it easy to expose an existing List as a read-only collection.
The Queue, Stack, and SortedList generic classes correspond to the respective non-generic classes with the
same names.
Windows Presentation Foundation (WPF): The Windows Presentation Foundation is Microsofts next generation UI
framework to create applications with a rich user experience. It is part of the .NET framework 3.0 and higher. WPF
combines application UIs, 2D graphics, 3D graphics, documents and multimedia into one single framework. Its vector
based rendering engine uses hardware acceleration of modern graphic cards. This makes the UI faster, scalable and
resolution independent.
WPF separates the appearance of a user interface from its behavior: The appearance is generally specified in
the Extensible Application Markup Language (XAML), the behavior is implemented in a managed programming
language like C# or Visual Basic. The two parts are tied together by data binding, events and commands. The
separation of appearance and behavior brings the following benefits:
Appearance and behavior are loosely coupled
Designers and developers can work on separate models.
Graphical design tools can work on simple XML documents instead of parsing code.
Rich composition: Controls in WPF are extremely compos able. You can define almost any type of controls as
content of another. Although these flexibility sounds horrible to designers, its a very powerful feature if you use it
appropriate. Put an image into a button to create an image button, or put a list of videos into a combo box to choose
a video file.
Highly customizable: Because of the strict separation of appearance and behavior you can easily change the look of
a control. The concept of styles let you skin controls almost like CSS in HTML. Templates let you replace the entire
appearance of a control.
Resolution independence: All measures in WPF are logical units - not pixels. A logical unit is a 1/96 of an inch. If you
increase the resolution of your screen, the user interface stays the same size - it just gets crispier. Since WPF builds
on a vector based rendering engine it's incredibly easy to build scalable user interfaces.

C# Programming

Ketan Rajpal

Page: 27

Creating a Simple WPF Application


Open Visual Studio 2008 and choose "File", "New", "Project..." in the main menu. Choose "WPF Application"
as project type.
Choose a folder for your project and give it a name. Then press "OK"
Visual Studio creates the project and automatically adds some files to the solution. A Window1.xaml and an
App.xaml. The structure looks quite similar to WinForms, except that the Window1.designer.cs file is no
longer code but it's now declared in XAML as Window1.xaml
Open the Window1.xaml file in the WPF designer and drag a Button and a TextBox from the toolbox to the
Window
Select the Button and switch to the event view in the properties window (click on the little yellow lightning
icon). Doubleclick on the "Click" event to create a method in the codebehind that is called, when the user
clicks on the button.
Visual Studio automatically creates a method in the code-behind file that gets called when the button is
clicked.
private void button1_Click(object sender, RoutedEventArgs e)
{
textBox1.Text = "Hello WPF!";
}

The textbox has automatically become assigned the name textBox1 by the WPF designer. Set text Text to
"Hello WPF!" when the button gets clicked and we are done! Start the application by hit [F5] on your
keyboard.

C# Programming

Ketan Rajpal

Page: 28

4th Unit
Introduction to XML: XML stands for Extensible Markup Language. XML is a markup language much like HTML. XML
was designed to carry data, not to display data. XML tags are not predefined. You must define your own tags. XML is
designed to be self-descriptive. Some of the important features of a XML document are
XML can be used to exchange, share, and store data.
XML documents form a tree structure that starts at "the root" and branches to "the leaves".
XML has very simple syntax rules. XML with correct syntax is "Well Formed". Valid XML also validates against
a DTD.
XSLT is used to transform XML into other formats like HTML.
All modern browsers have a built-in XML parser that can read and manipulate XML.
The DOM (Document Object Model) defines a standard way for accessing XML.
The XMLHttpRequest object provides a way to communicate with a server after a web page has loaded.
XML Namespaces provide a method to avoid element name conflicts.
Text inside a CDATA section is ignored by the parser.
The Difference between XML and HTML: All XML Elements Must Have a Closing Tag. XML Tags are Case Sensitive.
XML Elements must be Properly Nested. XML Documents Must Have a Root Element. XML Attribute Values must be
quoted. All modern browsers have a built-in XML parser. An XML parser converts an XML document into an XML
DOM object - which can then be manipulated with JavaScript. XML is not a replacement for HTML. XML and HTML
were designed with different goals. XML was designed to transport and store data, with focus on what data is. HTML
was designed to display data, with focus on how data looks. HTML is about displaying information, while XML is
about carrying information.
Usage of XML
XML Separates Data from HTML
XML Simplifies Data Sharing
XML Simplifies Data Transport
XML Simplifies Platform Changes
XML Makes Your Data More Available
XML is Used to Create New Internet Languages
Example of XML
<?xml version="1.0" encoding="ISO-8859-1"?>
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>

Valid XML Documents


XML Document
<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE note SYSTEM "Note.dtd">
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>

XML DTD
<!DOCTYPE note
[
<!ELEMENT note (to,from,heading,body)>
<!ELEMENT to (#PCDATA)>
<!ELEMENT from (#PCDATA)>

C# Programming

Ketan Rajpal

Page: 29

<!ELEMENT heading (#PCDATA)>


<!ELEMENT body (#PCDATA)>
]>

XML Schema
<xs:element name="note">
<xs:complexType>
<xs:sequence>
<xs:element name="to" type="xs:string"/>
<xs:element name="from" type="xs:string"/>
<xs:element name="heading" type="xs:string"/>
<xs:element name="body" type="xs:string"/>
</xs:sequence>
</xs:complexType>
</xs:element>

LINQ: Language Integrated Query (LINQ) gives .NET developers the ability to query and transform data using any
.NET language of choice. The data may be present in XML documents, inside relational database tables, or inside
collections of objects. LINQ is integrated into the .NET languages like C# and VB.
Query expressions can be used to query and to transform data from any LINQ-enabled data source.
Query expressions are easy to master because they use many familiar C# language constructs.
The variables in a query expression are all strongly typed, although in many cases you do not have to provide
the type explicitly because the compiler can infer it.
A query is not executed until you iterate over the query variable in a foreach statement.
Example of a LINQ Query
class LINQQueryExpressions
{
static void Main()
{
int[] scores = new int[] { 97, 92, 81, 60 };
IEnumerable<int> scoreQuery =
from score in scores
where score > 80
select score;
foreach (int i in scoreQuery)
{
Console.Write(i + " ");
}
}
}

The example will display the output: 97 92 81


Example of a LINQ Query
string[] tools = { "Tablesaw", "Bandsaw", "Planer", "Jointer", "Drill","Sander};
var list = from t in tools
select t;
StringBuilder sb = new StringBuilder();
foreach (string s in list)
{
sb.Append(s + Environment.NewLine);
}
MessageBox.Show(sb.ToString(), "Tools");

LINQ Providers
LINQ to Objects
LINQ to XML (formerly called XLINQ)
LINQ to SQL (formerly called DLINQ)
LINQ to DataSets
Other providers

C# Programming

Ketan Rajpal

Page: 30

LINQ to Objects: The LINQ to Objects provider is used for in-memory collections, using the local query execution
engine of LINQ. The code generated by this provider refers to the implementation of the standard query operators
as defined on the Sequence pattern and allows IEnumerable<T> collections to be queried locally. Current
implementation of LINQ to Objects uses e.g. O(n) linear search for simple lookups, and is not optimized for complex
queries.
Simple Example of LINQ to Objects
string[] Birds = { "Indigo Bunting", "Rose Breasted Grosbeak", "Robin",
"House Finch", "Gold Finch", "Ruby Throated
Hummingbird","Rufous Hummingbird", "Downy Woodpecker"
};
var list = from b in Birds
where b.StartsWith("R")
select b;
StringBuilder sb = new StringBuilder();
foreach (string s in list)
{
sb.Append(s + Environment.NewLine);
}
MessageBox.Show(sb.ToString(), "R Birds");

LINQ to XML (formerly called XLINQ): The LINQ to XML provider converts an XML document to a collection of
XElement objects, which are then queried against using the local execution engine that is provided as a part of the
implementation of the standard query operator.
Example 1
XElement xml = new XElement("contacts",
new XElement("contact",
new XAttribute("contactId", "2"),
new XElement("firstName", "Barry"),
new XElement("lastName", "Gottshall")
),
new XElement("contact",
new XAttribute("contactId", "3"),
new XElement("firstName", "Armando"),
new XElement("lastName", "Valdes")
)
);
Console.WriteLine(xml);

The example will display the output:


<contacts>
<contact contactId="2">
<firstName>Barry</firstName>
<lastName>Gottshall</lastName>
</contact>
<contact contactId="3">
<firstName>Armando</firstName>
<lastName>Valdes</lastName>
</contact>
</contacts>

Example 2
<contacts>
<contact contactId="2">
<firstName>Barney</firstName>
<lastName>Gottshall</lastName>
</contact>
<contact contactId="3">

C# Programming

Ketan Rajpal

Page: 31

<firstName>Armando</firstName>
<lastName>Valdes</lastName>
</contact>
<contact contactId="4">
<firstName>Adam</firstName>
<lastName>Gauwain</lastName>
</contact>
...
</contacts>

The C# Code:
var xmlSource = contacts.Load(@"../../Contacts.xml");
var q = from c in xmlSource.contact
where c.contactId < 4
select c.firstName + " " + c.lastName;
foreach(string name in q)
Console.WriteLine("Customer name = {0}", name);

The example will display the output:


Customer name = Barney Gottshall
Customer name = Armando Valdes

LINQ to SQL (formerly called DLINQ): The LINQ to SQL provider allows LINQ to be used to query SQL Server
databases, including SQL Server Compact databases. Since SQL Server data may reside on a remote server, and
because SQL Server has its own query engine, LINQ to SQL does not use the query engine of LINQ. Instead, it
converts a LINQ query to a SQL query that is then sent to SQL Server for processing. However, since SQL Server
stores the data as relational data and LINQ works with data encapsulated in objects, the two representations must
be mapped to one another. For this reason, LINQ to SQL also defines a mapping framework. The mapping is done by
defining classes that correspond to the tables in the database, and containing all or a subset of the columns in the
table as data members. The correspondences, along with other relational model attributes such as primary keys, are
specified using LINQ to SQL-defined attributes.
Example of LINQ to SQL
myLINQDBDataContext db=new myLINQDBDataContext();

To retrieve data from the database


var q=from products_1 in db.products
where products_1.category.categoryName==Bevrages
orderby products_1.productName
select products_1;
foreach (var x in q)
System.console.writeline(x.ProductName);

To update data from the database


Product p=q.ElementAtovDefault(10);
if(p!=null)
{
System.console.writeLine(p.productName, p.unitPrice);
p.UnitPrize-20;
}

To insert data in the database


Product p=new Product { Product Name=new Test Record};
db.Product.InsertOnSubmit(map);
db.SubmitChanges();

To delete data from the database

C# Programming

Ketan Rajpal

Page: 32

var p=from product_1 in db.product


where product_1.name==ABC
select product_1;
if(p!==null)
{
Db.product.DeleteOnSubmit(p);
Db.SubmitChanges();
}

LINQ to Datasets: The LINQ to SQL provider works only with Microsoft SQL Server databases; to support any generic
database, LINQ also includes the LINQ to Datasets, which uses ADO.NET to handle the communication with the
database. Once the data is in ADO.NET Datasets, LINQ to Datasets execute queries against these datasets.
Implicitly Typed Local Variable: Theres another language feature known as implicitly typed local variables (or var for
short) that instructs the compiler to infer the type of a local variable. For example:
var integer = 1;

In this case, integer has the type int. Its important to understand that this is still strongly typed. In a dynamic
language, integers type could change later. To illustrate this, the following code does not compile:
var integer = 1;
integer = hello;

The C# compiler will report an error on the second line, stating that it cant implicitly convert a string to an int.
implicitly typed locals are just that: local within a method. It is not possible for them to escape the boundaries of a
method, property, indexer, or other block because the type cannot be explicitly stated, and "var" is not legal for
fields or parameter types. Implicitly typed locals turn out to be convenient outside of the context of a query. For
example, it helps simplify complicated generic instantiations:
var customerListLookup = new Dictionary<string, List<Customer>>();

Anonymous Types: This language feature enables us to define inline types without having to explicitly define a class
declaration for this type. In other words, imagine we want to use a Point object without defining the class Point (it
would be anonymous).
var p = new {X = 0, Y = 2};

Extension Methods: Extension methods make it possible to extend existing types and constructed types with
additional methods, without having to derive from it or recompile the original type. So instead of writing helper
methods for objects they become part of that object itself.
As an example, suppose we want to check a string to see if it is a valid email address. We would do this by writing a
function that takes a string as an argument and returns a true/false.
We defined a static class with a static method containing the extension method. Note how the static method above
has a this keyword before the first parameter argument of type string. This tells the compiler that this particular
Extension Method should be added to objects of type string. And then we can call it from the string as a member
function.
An Example of Extension Methods
public static class MyExtensions {
public static bool IsValidEmailAddress(this string s) {
Regex regex = new Regex( @"^[w-.]+@([w-]+.)+[w-]{2,4}$" );
return regex.IsMatch(s);
}
}
using MyExtensions;
string email = Request.QueryString["email"];

C# Programming

Ketan Rajpal

Page: 33

if ( email.IsValidEmailAddress() ) {
// ...
}

Lambda expression: A lambda expression is an anonymous function that can contain expressions and statements,
and can be used to create delegates or expression tree types. All lambda expressions use the lambda operator =>,
which is read as "goes to". The left side of the lambda operator specifies the input parameters. The right side holds
the expression or statement block. The lambda expression x => x * x is read "x goes to x times x."
delegate int del(int i);
static void Main(string[] args)
{
del myDelegate = x => x * x;
int j = myDelegate(5); //j = 25
}

ADO.Net: ADO.NET provides consistent access to data sources such as Microsoft SQL Server, as well as data sources
exposed through OLE DB and XML. Data-sharing consumer applications can use ADO.NET to connect to these data
sources and retrieve, manipulate, and update data. ADO.NET is conceptually divided into consumers and data
providers. The consumers are the applications that need access to the data, and the providers are the software
component that implement the interface and thereby provides the data to the consumer. The data access
technologies used with ADO.net is
RDBMS
ADO (ADO vs. ADO.NET)
ODBC
JDBC
OLE DB
XML
The ADO.NET classes are found in System.Data.dll, and are integrated with the XML classes found in System.Xml.dll.
When compiling code that uses the System.Data namespace, reference both System.Data.dll and System.Xml.dll.

S-ar putea să vă placă și