You are on page 1of 80

C# and ASP .

NET

Copyright 2003 Compudava

Agenda
Introducing .NET Introducing C# language Basic Data-Access Techniques Developing and Implementing Web Applications Developing XML Web Services Making the Web Applications Available to Users
Copyright 2003 Compudava

OOP and .NET


Programming Techniques OOP concepts Object relationships .NET Overview .NET Architecture Introducing Assemblies

Copyright 2003 Compudava

Survey of Programming Techniques


Unstructured Programming Procedural Programming Modular Programming Object-Oriented Programming

Copyright 2003 Compudava

Unstructured Programming
program main program data

Unstructured programming. The main program directly operates on global data.

Copyright 2003 Compudava

Procedural Programming
Main program procedure program main program data

procedure1

procedure2

procedure3

Execution of procedures. After processing flow of controls proceed where the call was made.

Procedural programming. The main program coordinates calls to procedures and hands over appropriate data as parameters.
Copyright 2003 Compudava

Modular Programming
program

main program data

data+data1

module1

data+data2

module2

procedure1

procedure2

procedure3

Modular programming. The main program coordinates calls to procedures in separate modules and hands over appropriate data as parameters.
Copyright 2003 Compudava

Modular Programming Problems


Explicit Creation and Destruction Decoupled Data and Operations Missing Type Safety Strategies and Representation

Copyright 2003 Compudava

Object Oriented Programming


program

object1 data

object4 data

object3 data

object2 data

Object-oriented programming. Objects of the program interact by sending messages to each other.
Copyright 2003 Compudava

Object Oriented Concepts


Abstraction Encapsulation Inheritance Polymorphism

Copyright 2003 Compudava

Objects
Objects are the basic entities in an object-oriented system. Each object is denoted by a name and has state. The variables within the object express everything about the object (state) and the methods specify how it can be used (behavior). A method is a function or procedure that has access to the internal state of the object needed to perform some operation.

Copyright 2003 Compudava

Abstraction or Handling Problems


The model defines an abstract view to the problem. This implies that the model focuses only on problem related stuff and that you try to define properties of the problem. These properties include: the data which are affected and the operations which are identified by the problem.
Abstraction

Problem

abstraction is the structuring of a nebulous problem into well-defined entities by defining their data and operations. Consequently, these entities combine data and operations. They are not decoupled from each other.

Model

Copyright 2003 Compudava

Abstract Data Types (ADT)


The data structure can only be accessed with defined operations. This set of operations is called interface and is exported by the entity. An entity with the properties just described is called an abstract data type.
abstract data type
abstract data structure operations interfaces

An ADT consists of an abstract data structure and operations. Only the operations are viewable from the outside and define the interface.
Copyright 2003 Compudava

Class
Objects with the same data structure (Attributes) and behavior (Methods or Operations) are grouped together (called a class ).

Each class describes a possibly infinite set of individual objects. Each object is said to be an instance of a class . Each instance of the class, has its own value for each attribute but shares the attribute names and operations with other instances of the class. Each attribute name is unique within a class (as apposed to being unique across all classes) so class Person and class Company may each contain an attribute called Address
Copyright 2003 Compudava

Encapsulation
The principle of hiding the used data structure and to only provide a well-defined interface is known as encapsulation. Encapsulation allows the programmer to present clearly specified interfaces around the services they provide. The programmer can decide what should be hidden and what is intended to be visible. Some advantages of encapsulation are:
Managing complexity Managing change Protecting data

Copyright 2003 Compudava

Encapsulation
Each class has two parts:
An Interface An Implementation.

The Interface is the implementation code for the external Interface i.e. in the diagram the body of the lion. The Implementation is the code that does all the operations, makes the interface look as if it is doing something. All the functions the lion does such as sleep, eat, hunt etc..)

Copyright 2003 Compudava

Inheritance
As objects do not exist by themselves but are instances of a CLASS, a class can inherit the features of another class and add its own modifications. (This could mean restrictions or additions to its functionality). Inheritance aids in the reuse of code. Classes can have 'Children' that is, one class can be created out of another class. The original or parent class is known as the SuperClass (or base class). The child class is known as the SubClass (or derived class).

Copyright 2003 Compudava

Inheritance
A SubClass inherits all the attributes and behaviors of the SuperClass, and may have additional attributes and behaviors.

Copyright 2003 Compudava

Single inheritance
The attributes and operations in the diagram below are for vehicle class, which the SubClass inherits. Extra operation is the land vehicle works only on Land and the water vehicle works only in water.

Copyright 2003 Compudava

Multiple inheritance
Multiple inheritance enables the subclass to inherit properties of more than one superclass and to merge their properties.

Copyright 2003 Compudava

Polymorphism
Polymorphism means the ability to request that the same Operations be performed by a wide range of different types of things. Effectively, this means that you can ask many different objects to perform the same action. Same methods in the base class can be called to perform different actions depending on the run-time context. Client does not worry about how derived class was instanced. Usually is done through interface inheritance.

Copyright 2003 Compudava

Summary
To view a program as a collection of interacting objects is a fundamental principle in object-oriented programming. Objects in this collection react upon receipt of messages, changing their state according to invocation of methods which might cause other messages sent to other objects. Questions?

Copyright 2003 Compudava

Relationships
A-Kind-Of relationship
class Point { attributes: int x, y methods: setX(int newX) getX() setY(int newY) getY() }
Circle a kind of Point

class Circle { attributes: int x, y, radius methods: setX(int newX) getX() setY(int newY) getY() setRadius(newRadius) getRadius() }

Knowing the properties of class Point we can describe a circle as a point plus a radius and methods to access it. Thus, a circle is a-kind-of point. However, a circle is somewhat more specialized.
Copyright 2003 Compudava

Relationships
Is-A relationship
The previous relationship is used at the class level to describe relationships between two similar classes. If we create objects of two such classes we refer to their relationship as an ``is-a'' relationship. Since the class Circle is a kind of class Point, an instance of Circle, say acircle, is a point . Consequently, each circle behaves like a point. For example, you can move points in x direction by altering the value of x. Similarly, you move circles in this direction by altering their x value.
Circle is-a Point

Copyright 2003 Compudava

Relationships
Part-Of relationship
You sometimes need to be able to build objects by combining them out of others. You already know this from procedural programming, where you have the structure or record construct to put data of various types together. Let's come back to our drawing program. You already have created several classes for the available figures. Now you decide that you want to have a special figure which represents your own logo which consists of a circle and a triangle. Thus, your logo consists of two parts or the circle and triangle are part-of your logo:
class Logo { attributes: Circle circle Triangle triangle methods: set(Point where)
}

Circle

part-of

Logo

part-of

Point

Copyright 2003 Compudava

Relationships
Has-A relationship
This relationship is just the inverse version of the part-of relationship. Therefore we can easily add this relationship to the part-of illustration by adding arrows in the other direction.

part-of Circle has-of Logo

part-of has-of Point

Copyright 2003 Compudava

Questions?

Copyright 2003 Compudava

Introducing .NET Framework

Copyright 2003 Compudava

Why .NET Framework?


Greater programmer productivity Easier to make Internet software More powerful and sensible languages Cross-language development The platform scales

Copyright 2003 Compudava

Microsofts .NET Framework


Multi-language development and execution environment for software components A strategy for creating, designing, and executing applications in a distributed architecture Based on non-proprietary standards Consumer of .NET software can be on any platform
Copyright 2003 Compudava

.NET Platform
New Application Programming Interface (API) provides an object-oriented layer on top of Windows. The .NET platform has been extended to encompass all the new Windows and Web technology from Microsoft including:
COM+
Transaction support

ASP .NET
Successor to ASP for Web Development

XML
Industry standard for extensible markup

Web Services protocol


SOAP, WSDL and UDDI
Copyright 2003 Compudava

.NET Features
New object-oriented, component-based languages
C# Visual Basic .NET

New tools
Visual Studio .NET

Includes a comprehensive class library Language platform is designed to support language independence
Program in any language that supports .NET API

Languages are integrated Polymorphism can be implemented across languages

Copyright 2003 Compudava

.NET Resources
Common Type System (CTS) makes language integration possible Supported all across of the .NET languages: classes, interfaces, delegates, references type, and value types Include s Common Language Specification (CLS) Platform sits on the top of the operating system Supports
C# Visual Basic .NET C++ Compiled Jscript.NET CLR provides an object oriented platform
Copyright 2003 Compudava

.NET Architecture
C# Source C++ Source VB.NET Source Other Source

C# Compiler
IL+Metadata

C++ Compiler
IL+Metadata

VB.NET Compiler
IL+Metadata

Other Compiler
IL+Metadata

Just-In-Time (JIT) Compiler

Common Language Runtime (CLR)


Native Code (Managed)

Copyright 2003 Compudava

IL Intermediate Language
IL+metadata is the output from compilation. IL is an assembly language for a stack-based, virtual, .NET CPU. IL is similar bytecode emitted by a Java compiler. IL is fully compiled before it is executed. IL was not designed with a particular programming language in mind. IL statements manipulate common types shared by all .NET languages. Common Type System (CTS) A .NET type is more than just a data type; .NET types are typically defined by classes that include both code and data members.
Copyright 2003 Compudava

CLR and JIT


CLR (Common Language Runtime) is responsible for loading and executing a .NET application. It employs a JIT (Just-InTime) compilation to translate the IL to native machine code. .NET code is always compiled, never interpreted. So .NET does not use a virtual machine to execute the program. Instead, the IL for each method is JIT-compiled when it is called for the first time. The next time the method is called, the JIT-compiled native code is executed. The compilation process produces a Windows executable file in portable executable (PE) format. This has two important implications:
First, the CLR neither knows, nor cares, what language was used to create the application or component. It just sees IL. Second, in theory, replacing the JIT compiler is all thats necessary to target a new platform.
Copyright 2003 Compudava

.NET Processes
Web Forms Web Services Windows Forms

Data/XML

.NET Framework
Common Language Runtime (CLR)

Windows platform
Copyright 2003 Compudava

Summary

Questions?

Copyright 2003 Compudava

Assembly Overview
A .NET application is packaged into an assembly, which is a set of one or more files containing types, metadata, and executable code. The .NET documentation describes the assembly as the smallest versionable, installable unit in .NET. It is the functional unit for code sharing and reuse. It is also at the center of .NETs code security and permissions model. All executable code must be part of an assembly. When we compile a simple program, the compiler creates an assembly consisting of a single executable file. However, assemblies can contain multiple files including code module files and files containing resources such as GIF images. Therefore, an assembly can be viewed as a logical DLL. The assembly contains a manifest that stores metadata describing the types contained in the assembly, and how they relate to one another. The runtime reads this manifest to retrieve the identity of the assembly, its component files and exported types, and information relating to other assemblies on which the assembly depends. When an assembly consists of multiple files, one file will contain the manifest.
Copyright 2003 Compudava

Creating a multifile assembly


Suppose we define a Person class using C# and save it to file called person.cs. We can compile it to a module, as follows:
csc /target:module /out:person.mod person.cs

The /target:module option tells C# to create a module target. Both C# and Visual Basic .NET compilers support four different types of target output: exe, winexe, library and module Now, suppose we define a People class using C# which creates Person objects and save it to file called people.cs.
csc /addmodule:person.mod people.cs

The /addmodule compiler option is used to link the person.mod module into the People assembly. This gives us a multifile assembly consisting of two module files, people.exe and person.mod. The assemblys manifest is contained in people.exe.
Copyright 2003 Compudava

Creating a multifile assembly

Assembly: People
Module: people.exe
Assembly Manifest Type Metadata IL Code

Module: person.exe
Type Metadata IL Code

Copyright 2003 Compudava

Day 2. C# Overview
Introduction Identifiers, variables and constants Arrays, types and operators C# statements Classes, structs and interfaces Delegates and events Inheritances and Polymorphism Exceptions Examples
Copyright 2003 Compudava

Introduction
Goal of C#
Provide a simple, safe, modern, object-oriented, Internetcentric, and high-performance language for .NET development

C#
Building blocks language Uses a limited set of keywords and constructs Type-safe language that catches bugs while compiling Builds a lessons in C++ and Java using object-oriented techniques Language for writing .NET applications The point of learning this language is to build Web and desktop applications on the .NET platform
Copyright 2003 Compudava

Structure of a C# program
namespace N1 { class C1 { // ... } struct S1 { // ... } interface I1 { // ... } delegate int D1(); enum E1 { // ... } } namespace N2 { class C2 { public static void Main (string[] args) { //execution starts here } } }

A C# program consists of one or more files, each of which can contain one or more namespaces, which in turn contain types. If no namespace is declared, then a default global namespace is assumed. An executable C# program must include a class containing a Main function member, or method, which represents the program entry point where execution begins. Any command-line arguments are passed as parameters to the Main method in the form of a zero-based array of strings.
Copyright 2003 Compudava

C# Identifiers
An identifier must start with a letter or underscore and consist of Unicode characters. Typically, an identifier will consist of letters, underscores, and decimal digits. C# identifiers are case sensitive. You cannot use a C# keyword as an identifier. However, you may prefix an identifier with the @ character to distinguish it from a keyword: object @this; // prevent clash with "this" keyword

Copyright 2003 Compudava

C# Variables
A C# variable represents a location in memory where an instance of some type is stored. There are no global variables in C#. Value types can be directly declared and initialized. C# has two methods for ensuring that variables are initialized before use: Variables that are fields in a class or struct, if not initialized explicitly, are by default zeroed out when they are created. Variables that are local to a method must be explicitly initialized in your code prior to any statement in which their values are used. In this case, the initialization doesnt have to happen when the variable is declared, but the compiler will check all possible paths through the method and will flag an error if it detects any possibility of the value of a local variable being used before it is initialized.
bool bln = true; char ch1 = 'x'; decimal d1 = 1.23M; double dbl1 = 1.23; short sh = 22; int i = 22; long lng1 = 22; sbyte sb = 22; float f = 1.23F; ushort us1 = 22; uint ui1 = 22; string s = "Hello";
Copyright 2003 Compudava

C# Constants
C# provides the const modifier which can be used in front of a declaration to create program constants:
const int min = 1; const int max = 100; const int range = max - min;

Constants are typically initialized with a literal value. They can also be given the value of an expression, as we do with the range constant above, provided that the compiler can evaluate the expression at compile time. Therefore, the following would generate a compiler error because the value of the expression assigned to i cannot be known until run time:
System.Random r = new System.Random(); const int i = r.Next(1, 7); //error - compiler cannot evaluate
Copyright 2003 Compudava

C# Arrays
Arrays in C# are zero-based and, for the most part, work like they do in other common programming languages. The array type is a reference type.
string[] a; string[]a1 = new string[1000]; string[] a2 = {cat,dog,mouse}; int[,] b3 = {{3,4},{4,7},{6,4}}; int[][] matrix = new int[3][]; matrix[0] = new int[] {1, 2, 3}; matrix[1] = new int[] {1, 2, 3, 4, 5}; matrix[2] = new int[] {1, 2}; object[] ar = {3,"cat,2.45}; string animal = (string)ar[1];

You cannot change the size of an array once it has been instantiated (other than by copying the contents to a new array). If you want to dynamically add elements to an array, you will have to create an instance of the ArrayList object, which is in the System.Collections namespace.
Copyright 2003 Compudava

C# Predefined Data Types


C# has two categories of data type:
Value types Reference types

Conceptually, the difference is that a value type stores its value directly, while a reference type stores a reference to the value. Value types are stored in an area known as the stack. Reference types are stored in an area known as the managed heap.
Copyright 2003 Compudava

Value vs. reference types


Value Types { int i=3; int j=i; } Reference Types { string s=hello; string t=s; }
stack i j 3 3

heap stack s h e l l o

Copyright 2003 Compudava

Integer types
Name sbyte short int long CTS Type System.SByte System.Int16 System.Int32 System.Int64 Description 8-bit signed integer 16-bit signed integer 32-bit signed integer 64-bit signed integer Range (min:max) -128:127 (-27:27-1) -32,768:32,767 (-215:215-1) -2,147,483,648:2,147,483,647 (-231:231-1) -9,223,372,036,854,775,808: 9,223,372,036,854,775,808 (-263:263-1) 0:255 (0:28-1) 0:65,535 (0:216-1) 0:4,292,967,295 (0:232-1) 0:18,446,744,073,709,551,615 (0:264-1)

byte ushort uint ulong

System.Byte System.UInt16 System.UInt32 System.UInt64

8-bit unsigned integer 16-bit unsigned integer 32-bit unsigned integer 64-bit unsigned integer

Copyright 2003 Compudava

Floating Point, Decimal, Boolean, Character and Reference Types


Name float double CTS Type System.Single System.Double Description Significant Figures Range (min:max) 1.510-45 to 3.41038 5.010-324 to 1.710308 1.010-28 to 7.91028

decimal System.Decimal

32-bit single-precision 7 floating-point 64-bit double-precision 15/16 floating-point 128-bit high precision 28 decimal notation Values

Name bool char Name object string

CTS Type System.Boolean System.Char CTS Type System.Object System.String

true or false Represents a single 16-bit (Unicode) chatacter Description The root type, from which all other types in the CTS derive (including value types) Unicode character string

Copyright 2003 Compudava

C# Operators
Category
Arithmetic Logical String concatenation Increment and decrement Bit shifting Comparison Assignment Member access (for objects and structs) Indexing (for arrays and indexers) Cast Conditional (the Ternary Operator) Object Creation Type information Overflow exception control Indirection and Address

Operator
+ - * / % & | ^ ~ && || ! + ++ -<< >> == != < > <= >= = += -= *= /= %= &= |= ^= <<= >>= . [] () ?: new sizeof (unsafe code only) is typeof as checked unchecked * -> & (unsafe code only) []
Copyright 2003 Compudava

checked and unchecked


are used to control overflow checking in arithmetic operations and conversions.
Example1: byte b=255; checked { b++; } Console.WriteLine (b.ToString()); Example2: byte b=255; unchecked unchecked { is the default b++; } Console.WriteLine (b.ToString()); In this case, no exception will be raised, but we will lose data since the byte type cant hold a value of 256, the overflowing bits will be discarded, and our b variable will hold a value of zero
Copyright 2003 Compudava

When we try to run this, we will get an error message like this: Arithmetic operation resulted in an overflow.

is, sizeof and typeof


The is operator allows us to check whether an object is compatible with a specific type (an object is either of that type or is derived from that type)
Example: int i=10; if (i is object) { Console.WriteLine("i is an object"); }

We can determinate the size (in bytes) required by a value type on the stack using the sizeof operator
Example: unsafe { Console.WriteLine(sizeof(int)); }

The typeof operator returns a Type object representing a specified type. This is useful when we want to use reflection to find out information about an object dynamically
Example: Console.WriteLine(typeof(string));

Copyright 2003 Compudava

Boxing and Unboxing


Boxing and unboxing allow us to convert value types to reference types and vice versa. Boxing is the term used to describe the transformation of a value type to a reference type. Unboxing is the term used to describe the reverse process, where the value of a reference type is to a value type.
Example: int i = 20; object o = i; // Box the int int j = (int)o; // Unbox it back into an int

When unboxing, we have to be careful that erceving value variable has enough room to store all the bytes in the value being unboxed. C#s ints, for example, are only 32 bits long, so unboxing a long value (64 bits) into an int as shown below will result in an InvalidCastException:
long a = 333333423; object b = (object)a; int c = (int)b;
Copyright 2003 Compudava

C# statements
C# statements are similar C, C++ or Java statements, excepting switch statement: C# provides the goto case and goto default, to allow multiple cases to execute the same statement block. Omitting the break statements causes a compiler error.
uint i = 2; switch(i) { case 0: goto case 1; case 1: goto case 2; case 2: Console.WriteLine("i<3"); break; case 3: Console.WriteLine("i==3"); break; default: Console.WriteLine("i>3"); break; }

Also C# introducing the foreach statement:

foreach (int temp in arrayOfInts) { Console.WriteLine(temp); }

We cant change the value of the item in the collection (temp above)

Copyright 2003 Compudava

C# Class definition
The fundamental building block of a C# application is the class. [attributes] [modifiers] class identifier [:base-list] { class-body }[;] Where: attributes (Optional) Additional declarative information. modifiers (Optional) The allowed modifiers are new, abstract, sealed, and the four access modifiers (public, protected, internal, private). The access levels protected and private are only allowed on nested classes. identifier The class name. base-list (Optional) A list that contains the one base class and any implemented interfaces, all separated by commas. class-body Declarations of the class members (Constructors, Destructors, Constants, Fields, Methods, Properties, Indexers, Operators, Events, Delegates, Classes, Interfaces, Structs).

Copyright 2003 Compudava

C# Class members
Classes contain Data members and Function members Data members are those members that contain the data for the class fields, constants, and events. Function members are those members that contain code methods, constructors, properties, and operator overloads Methods
The syntax for defining and invoking a method in C# is virtually identical to the syntax in C++ and Java. Arguments can in general be passed into methods by reference, or by value. A variable that is passed by reference to a method is affected by any changes that called method makes to it, while a variable that is passed by value to a method is not changed by any changes made within the body of the method. Since reference types only hold a reference to an object, they will still only pass this reference into the method. Value types, in contrast, hold the actual data, so a copy of the data itself will be passed into the method.
Copyright 2003 Compudava

Access Modifiers
Access modifiers are keywords used to specify the declared accessibility of a member or a type. There are four access modifiers: public, protected, internal, private. public access is the most permissive access level. There are
no restrictions on accessing public members. A protected member is accessible from within the class in which it is declared, and from within any class derived from the class that declared this member. A protected member of a base class is accessible in a derived class only if the access takes place through the derived class type. internal members are accessible only within files in the same assembly. private access is the least permissive access level. Private members are accessible only within the body of the class or the struct in which they are declared. Nested types in the same body can also access those private members.
Copyright 2003 Compudava

Constructors
A constructor is a method that is invoked upon instantiation of a class. We declare a method that has the same name as the containing class, and which does not have any return type. If you dont explicitly supply any constructor, the compiler will just make a default one up for you behind the scenes. Itll be a very basic constructor that just initializes all the member fields to their normal default values (empty string for strings, zero for numeric data types, and false for bools). You can provide as many overloads to the constructor as you wish, providing they are clearly different in signature. If you supply any constructors that take parameters, then the compiler will not automatically supply a default one. It is possible to define constructors as private or protected. This is useful in two situations:
If your class serves only as a container for some static members or properties, and therefore should never be instantiated; If you want the class to only ever be instantiated by calling some static member function.

If you declare only one or more private constructors, you will also make it impossible for any class derived from your class to ever be instantiated by any means whatsoever.
Copyright 2003 Compudava

Calling Constructors from Other Constructors


You may sometimes find yourself in the situation where you have several constructors in a class, perhaps to accommodate some optional parameters, for which the constructors have some code in common. For example, both constructors initialize the same fields
class Car { private string description; private uint nWheels; public Car(string description, uint nWheels) { this.description = description; this.nWheels = nWheels; } public Car(string description): this(description,4) { } }
Copyright 2003 Compudava

class Car { private string description; private uint nWheels; public Car(string description, uint nWheels) { this.description = description; this.nWheels = nWheels; } public Car(string description) { this.description = description; this.nWheels = 4; } }

Method Overloading
C# supports method overloading, which allows a class, struct, or interface to declare multiple methods with the same name, provided the signatures of the methods are all different. Constructor methods can be overloaded too. C# does places some minimum differences on the parameters of overloaded methods:
It is not sufficient for two methods to differ only in their return type It is not sufficient for two methods to differ by virtue of a parameter having been declared as ref or out.

Copyright 2003 Compudava

Method Overriding and Hiding

By declaring a base class function as virtual, we allow the function to be overridden in any derived class. In C#, functions are not virtual by default, but (aside from constructors) may be explicitly declared as virtual. C# differs from C++ syntax, however, because it requires you to explicitly declare when a derived classs function overrides another function, using override keyword.

If a method with the same signature is declared in both base and derived classes, but the methods are not declared as virtual and override respectively, then the derived class version is said to hide the base class version. The result is that which version of a method gets called depends on the type of the variable used to reference the instance, not the type of the instance itself. In most cases you would want to override methods rather than them, because hiding them gives a strong risk of the wrong method being called for a given class instance. In C#, we should use the new keyword to declare that we intend to hide a method.

Copyright 2003 Compudava

Inheritance
C# allows us to design a class by using inheritance to embrace and extend an existing class. C# supports only single inheritance. C# supports the concept of a universal base class, System.Object, from which all other classes are ultimately derived. If you do not specify a base class in your class definition, the C# compiler will assume that System.Object is the base class. A class inherits the members of its direct base class. Inheritance means that a class implicitly contains all members of its direct base class, except for the instance constructors, destructors and static constructors of the base 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 member it merely makes that member inaccessible directly through the derived class.
Copyright 2003 Compudava

Interfaces
An interface may inherit from multiple base interfaces, and a class or struct may implement multiple interfaces. An interface can be a member of a namespace or a class and can contain signatures of the following members: Methods, Properties, Indexers, Events An interface can inherit from one or more base 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. When a class base list contains a base class and interfaces, the base class comes first in the list.
Copyright 2003 Compudava

C# Interface definition
An interface defines a contract. A class or struct that implements an interface must adhere to its contract. [attributes] [modifiers] interface identifier [:base-list] {interface-body}[;] Where: attributes (Optional) Additional declarative information. modifiers (Optional) The allowed modifiers are new and the four access modifiers (public, protected, internal, private). identifier The interface name. base-list (Optional) A list that contains one or more explicit base interfaces separated by commas. interface-body Declarations of the interface members.

Copyright 2003 Compudava

C# Properties
Properties are an extension of fields and are accessed using the same syntax. Unlike fields, properties do not designate storage locations. Instead, properties have accessors that read, write, or compute their values. [attributes] [modifiers] type identifier {accessor-declaration} [attributes] [modifiers] type interface-type.identifier {accessor-declaration} Where: attributes (Optional) Additional declarative information. modifiers (Optional) The allowed modifiers are new, static, virtual, abstract, override, and a valid combination of the four access modifiers. type The property type, which must be at least as accessible as the property itself. identifier The property name. accessor-declaration Declaration of the property accessors, which are used to read and write the property. interface-type The interface in a fully qualified property name.
Copyright 2003 Compudava

The Object Class


Supports all classes in the .NET Framework class hierarchy and provides low-level services to derived classes. This is the ultimate base class of all classes in the .NET Framework; it is the root of the type hierarchy. In C#, if you dont specify that a class is derived from another class, the compiler will automatically assume that it derives from Object. The practical significance of this is that, besides the methods and properties and so on that you define, you also have access to a number of public and protected member methods that have been defined for the Object class. These methods are available in all other classes that you define.

Copyright 2003 Compudava

Object Class members


Method string ToString() int GetHashTable() bool Equals(object obj) bool ReferenceEquals(object objA, object objB) Type GetType() Access Modifiers public virtual public virtual public virtual public static Pupose Returns a string representation of the object Used if implementing dictionares (hash tables) Compares instances of the object forequality Compares instances of the object for equaity Returns details of the type of the object Makes a shallow copy of the object

public

object MemberwiseClone() protected void Finalise()

protected virtual This is the .NET version of a destructor


Copyright 2003 Compudava

The out and ref keyword


C# provides ref and out parameters to enable value types to be passed by reference. Use the ref keyword to specify that an initialized value should be passed by reference. The ref keyword must be used both in the call and in the method signature. The ref keyword is used to allow the modification, by a method, of an existing initialized variable. If, instead, the method assigns the initial value to the variable, you should use the out keyword.
void Increment(ref int i) { i++; } ... int i = 0; // initialized Increment(ref i); // now i==1 void Increment(out int i) { i=5; } ... int i; // uninitialized Increment(out i); // now i==5

Also, i must first be initialized before being passed as a parameter to Increment.


Copyright 2003 Compudava

static Constructors
One novel feature of C# is that it is also possible to write a static noparameter constructor for a class. Such a constructor will only ever be executed once, as opposed to the constructors weve written so far, witch are instance constructors, and executed whenever an object of that class is created. One reason for writing a static constructor would be if your class has some static fields or properties that need to be initialized from an external source before the class is first used. The .NET runtime makes no guarantees about when a static constructor will be executed. In C#, the static constructor usually seems to be executed immediately before the first call to a member of the class. The static constructor does not have any access modifiers, cannot ever take any parameters, can only access static members, and there can only ever be one static constructor for a class. It is possible to have a static constructor and zero-parameter instance constructor defined in the same class. Although the parameter lists are identical, there is no conflict here because the static constructor is executed when the class is loaded, but the instance constructor is executed whenever an instance is created.
Copyright 2003 Compudava

C# struct definition
A struct type is a value type that can contain constructors, constants, fields, methods, properties, indexers, operators, events, and nested types [attributes] [modifiers] struct identifier [:interfaces] body [;] Where: attributes (Optional) Additional declarative information. modifiers (Optional) The allowed modifiers are new and the four access modifiers (public, protected, internal, private). identifier The struct name. interfaces (Optional) A list that contains the interfaces implemented by the struct, all separated by commas. body The struct body that contains member declarations.

Copyright 2003 Compudava

Differences between classes and structs


Structs are value types, not reference types. This means they are stored either in the stack or inline (if they are part of another object that is stored on the heap), and have the same lifetime restrictions as the simple data types. Structs do not support inheritance. The only exceptions to this is that structs, in common with every other types in C#, derive ultimately from the class System.Object and have access to the methods of System.Object, and it is even possible to override them in structs. There are some differences in the way constructors work for structs. In particular, the compiler always supplies a default no-parameter constructor, which you are not permitted to replace. With a struct, you can (if you wish) specify how the fields are to be laid out in memory.
Copyright 2003 Compudava

abstract Modifier

The abstract modifier can be used with classes, methods, properties, indexers, and events. Use the abstract modifier in a class declaration to indicate that a class is intended only to be a base class of other classes. Abstract classes have the following features:
An abstract class cannot be instantiated. It is not possible to modify an abstract class with the sealed modifier, which means that the class cannot be inherited. A non-abstract class derived from an abstract class must include actual implementations of all inherited abstract methods and accessors.

Use the abstract modifier in a method or property declaration to indicate that the method or property does not contain implementation. Abstract methods have the following features:
An abstract method is implicitly a virtual method. Abstract method declarations are only permitted in abstract classes. Because an abstract method declaration provides no actual implementation, there is no method body It is an error to use the static or virtual modifiers in an abstract method declaration.
Copyright 2003 Compudava

sealed Modifier
A sealed class cannot be inherited. It is an error to use a sealed class as a base class. Use the sealed modifier in a class declaration to prevent inheritance of the class. It is not permitted to use the abstract modifier with a sealed class. Structs are implicitly sealed; therefore, they cannot be inherited.

Copyright 2003 Compudava

Operator Overloading

C# allows user-defined types to overload operators by defining static member functions using the operator keyword. Where you might want to write overloads for operators?
From the world of mathematics, almost any mathematical object: coordinates, vectors, matrices, functions, and so on. Graphics programs will also use mathematical or coordinate-related objects when calculating positions on screen. A class that represents an amount of money A word processing or text analysis program might have classes representing sentences, clauses, and so on, and you might wish to use operators to combine sentences together (a more sophisticated version of concatenation for strings).

Which Operators Can You Overload?


Category Arithmetic binary Arithmetic unary Bitwise binary Bitwise unary Comparison Operators +, *, /, -, % +, -, ++, -&, |, ^, <<, >> !, ~, true, false ==, !=, >, >=, <, <= Restrictions none none none none must be overloaded in pairs
Copyright 2003 Compudava

C# Indexers
Indexers permits your classes to be treated as arrays. An indexer is a member that enables an object to be indexed in the same way as an array. Whereas properties enable field-like access, indexers enable array-like access. [attributes] [modifiers] indexer-declarator {accessor-declarations}

Where: attributes (Optional) Additional declarative information. modifiers (Optional) Allowed modifiers are new, virtual, sealed, override, abstract, extern, and a valid combination of the four access modifiers. indexer-declarator Includes the type of the element introduced by the indexer, this, and the formal-index-parameter-list. type A type name. accessor-declarations The indexer accessors, which specify the executable statements associated with reading and writing indexer elements. identifier The parameter name

Copyright 2003 Compudava

Indexers Accessor Declaration


get Accessor The get accessor body of an indexer is similar to a method body. It returns the type of the indexer. The get accessor uses the same formal-index-parameter-list as the indexer. For example: get { return myArray[index]; } set Accessor The set accessor body of an indexer is similar to a method body. It uses the same formal-index-parameter-list as the indexer, in addition to the value implicit parameter. For example: Set { myArray[index] = value; }
Copyright 2003 Compudava

C# Delegates
A delegate declaration defines a reference type that can be used to encapsulate a method with a specific signature. A delegate instance encapsulates a static or an instance method. [attributes] [modifiers] delegate result-type identifier ([formalparameters]); Where: attributes (Optional) Additional declarative information. modifiers (Optional) The allowed modifiers are new and the four access modifiers. result-type The result type, which matches the return type of the method. identifier The delegate name. formal-parameters (Optional) Parameter list. If a parameter is a pointer, the delegate must be declared with the unsafe modifier.

Copyright 2003 Compudava

You might also like