Sunteți pe pagina 1din 12

Agenda

? What is C# ?
? Some C# FAQs
C# - An Introduction ? C# Features

? Windows Forms

? Web Forms
- Parag Godkar

National Centre for Software National Centre for Software


10/26/2002 Technology 1 10/26/2002 Technology 2

What is C# ? Basic Requirements for C#


? Install Microsoft .Net SDK.
? Developed by Anders Hejlsberg and is one of
the languages designed for the .NET ? Any basic editor – TextPad
platform. recommended.
C# (pronounced C sharp) is a simple,
? Windows Forms Programming – Visual
?
modern, object oriented, and type-safe
programming language derived from C and Studio.Net
C++. ? Web Forms – Visual Studio.Net and IIS.
? C# aims to combine the high productivity of
Visual Basic, the raw power of C++ and the
elegance of Java.

National Centre for Software National Centre for Software


10/26/2002 Technology 3 10/26/2002 Technology 4

Agenda
? What is C# ?
? Some C# FAQs
Demo: First Program ? C# Features

? Windows Forms

? Web Forms
Keeping in line with the tradition –
The Hello World Program

National Centre for Software National Centre for Software


10/26/2002 Technology 5 10/26/2002 Technology 6

1
Some C# FAQs Some C# FAQs
? Is C# a new version of C++ ?
? No, It is a totally new object oriented ? Does C# support RAD ( Rapid
language built from the ground up to Application Development ) like VB ?
support .Net Framework. ? Yes, it does. It supports drag, drop and
? The syntax is similar to that of C++. build features of VB.
? How does C# relate to Java ? ? Where do I get a C# Compiler ?
? The .Net Framework SDK includes it.
? Java Programmers will find it easy to
migrate to C#. ? It is not yet distributed individually.
? Third Parties are free to write their own
? The concepts are similar to Java.
compilers.
National Centre for Software National Centre for Software
10/26/2002 Technology 7 10/26/2002 Technology 8

Some C# FAQs Some C# FAQs


? How to run C# Programs on Client’s ? Is C# Platform Independent ?
Machine ? ? Yes, for the Windows Platforms – Win
? There is a separate .NET Redistributable 98/ME and Win NT/2000/XP.
runtime (20 MB) available, which can be ? No for other platforms. But, Microsoft plans
used to install on the client's machine. to release .Net runtime for other platforms
? Sounds like Java VM ?? soon.
? Third Party efforts are on - www.go-
mono.com.

National Centre for Software National Centre for Software


10/26/2002 Technology 9 10/26/2002 Technology 10

Some C# FAQs Agenda


? Is C# an open standard ? ? What is C# ?
? Yes, C# and the CLI specifications were ? Some C# FAQs
submitted by Microsoft to the ECMA
? C# Features
(European Computer Manufacturer’s
Association) , and they have been ratified ? Windows Forms

as standards. ? Web Forms


? Why is C# called as C Sharp and not as
C Hash ?
? Microsoft knows.

National Centre for Software National Centre for Software


10/26/2002 Technology 11 10/26/2002 Technology 12

2
C# Features C# Features
Type System Type System

? Present Scenario –
? Different languages have their own ? In .Net and therefore in C#, types are
implementation of data types. grouped into two -
? This difference makes software ? Value types
interoperability very difficult. ? Reference types
? .Net Framework – ? Value and Reference types differ into
two characteristics –
? Standard representation and range limit for
? Where they are stored in memory.
a data type for all languages supporting
.Net Framework. ? How they behave in the context of the
assignment statements.
National Centre for Software National Centre for Software
10/26/2002 Technology 13 10/26/2002 Technology 14

C# Features
Type System C# Features Type System - Value Types

? Value types are stored on the stack, ? Allows you to store values in a variable
and assignment statements between with a certain type.
two values variables result in two
? It is a reserved space in memory and
separate, but identical, copies of the
value in memory. your program directly manipulates data
stored in that space.
? Reference types are stored on the
heap, and an assignment statement ? Value types include signed and

between two reference variables results unsigned.


in two references to a single value at
one location in memory.
National Centre for Software National Centre for Software
10/26/2002 Technology 15 10/26/2002 Technology 16

C# Features Type System - Value Types C# Features Type System - Reference Types

? Value types are further grouped into five - ? In C#, all objects are defined as reference
? Integral type: sbyte, byte, short, ushort, int, uint, types.
long, ulong and char ? Although technically it is still a pointer, you
? Floating point types: float and double are prevented to manipulate it like a pointer.
? Decimal type: decimal You can forget your pointer maths in C#.
? Bool type: bool ? They are type -safe pointers meaning that
? Enumeration type: enum instead of merely being an address, which
might or might not point to what you think it
? E.g. – does, a reference (when not null) is always
enumerators, structures and primitive types guaranteed to point to an object that is of the
type specified and that has already been
allocated on the heap.
National Centre for Software National Centre for Software
10/26/2002 Technology 17 10/26/2002 Technology 18

3
C# Features Type System - Reference Types C# Features Everything is an Object

? C# uses the new keyword to create an ? Everything in the CTS is an object.


object, which is similar to C++. However in ? All objects implicitly derive from a single base
C#, the keyword means to instantiate a class class defined as part of the Common Type
and not a specific instruction to allocate System (CTS). This base class, called
memory. System.Object.
? The reason behind this is because .Net and ? It has 4 methods –
C# has a garbage collector, which manages ? ToString()
the allocation and release of memory. ? Equals()
? E.g. - ? GetHasCode()
classes, arrays, delegates, and interfaces ? GetType()

National Centre for Software National Centre for Software


10/26/2002 Technology 19 10/26/2002 Technology 20

C# Features Boxing and UnBoxing C# Features Boxing and UnBoxing

? Boxing: ? Boxing:
Conversion of Value Type to a Reference Type.
?
? E.g.:
? UnBoxing:
int n = 4; // value type
? Conversion of Reference Type to a Value Type.
object obj = n; // ‘n’ is boxed to
? All types in C# are objects.
‘obj’
? They are objects only when they need to be,
thereby avoiding the overhead required if
? When the compiler finds a value type
everything actually were an object. where it needs a reference type, it
creates an object “box” into which it
places the value of the value type.
National Centre for Software National Centre for Software
10/26/2002 Technology 21 10/26/2002 Technology 22

C# Features
C# Features Boxing and UnBoxing object and string

? UnBoxing: ? E.g.:
? E.g.: int n = 4;
int n = 4; // value type
string s = n. ToString() // call
object obj = n; // create a ‘box’ to hold n
Object. ToString ()
int m = (int)obj; // unbox n
? C# provides with two different reference types
? We need an explicit cast while unboxing as
– object and string. All other classes are based
‘obj’ could be referring to any kind of object
on object even if they don’t claim inheritance
and the compiler must verify the type.
from any other class.

National Centre for Software National Centre for Software


10/26/2002 Technology 23 10/26/2002 Technology 24

4
C# Features C# Features
Classes Classes

? Classes are at the heart of every object- ? C++ Note –


oriented language. ? No semicolon needed at the end of class
? Used for encapsulation of data and the definition.
methods that work on that data. ? Java Note –
? C# borrows a little from C++ and Java and ? Unlike Java, C# classes are defined and
adds some ingenuity to create elegant implemented in the same place.
solutions to old problems. ? Every C# application must have a Main
method defined as a method in one of
its classes. In addition, this method
must be defined as public and static.
National Centre for Software National Centre for Software
10/26/2002 Technology 25 10/26/2002 Technology 26

C# Features C# Features
Classes Properties

? It doesn't matter to the C# compiler


which class has the Main method ? It is bad practice in OOPs to give users of a
defined, nor does the class you choose class public access to Data Members (Class
affect the order of compilation. Fields) – for reasons of data integrity.
? The designers of C# included a ? Solution – ‘set and get’ – Accessor Methods.
mechanism by which you can define ? Two Drawbacks –
more than one class with a Main ? Code the accessor methods manually.
method. Why would you want to do ? Users have to figure out that they have to use
that? One reason is to place test code accessor methods.
in your classes.
National Centre for Software National Centre for Software
10/26/2002 Technology 27 10/26/2002 Technology 28

C# Features C# Features
Properties Properties

? C# Solution - ‘set and get’ code built into the ? Demo


language and called Properties.
? Difference to the user – it appears as if they ? The accessor methods provided by a Property
have direct access to the data members (as if are called Setter and Getter Methods.
the fields are public).
? A property can be readonly by omitting the
? In reality the compiler maps the call onto setter method.
set/get built -in get/set methods.
? The idea of Properties was borrowed from
Visual Basic.
National Centre for Software National Centre for Software
10/26/2002 Technology 29 10/26/2002 Technology 30

5
C# Features C# Features
Properties Arrays

? A property can be decorated with ? In C#, Arrays are objects that have
virtual, overide and abstract modifiers, System.Array defined as their base class.
enabling a derived class to inherit and ? So defining an Array causes instantiation of
overide properties. System.Array class inheriting all it’s members.
? Declaring an Array –
? E.g. – int[] number
? Because properties provide a generic ? An Array is not actually created until you
and intuitive way of accessing data instantiate it just like a class.
members – object.field – they are
sometimes called as Smart Fields.
National Centre for Software National Centre for Software
10/26/2002 Technology 31 10/26/2002 Technology 32

C# Features C# Features
Arrays Arrays

? Declaring and Instantiating an Array –


? E.g. – int[] number = new int[7] ? E.g. –
---- single dimensional array of 7 integers. class MyClass
{
int[] number;
? When declaring an array as a member of a
class, you need to instantiate the array in two void SomeMethod()
{
distinct steps because you can’t instantiate an number = new int[7];
object until runtime. }
}
? Demo

National Centre for Software National Centre for Software


10/26/2002 Technology 33 10/26/2002 Technology 34

C# Features C# Features
Indexers Indexers

? C# specific feature that enables one to ? Being related to properties, it makes sense
programmatically treat objects as to have similar syntax.
though they were arrays. ? Defining Indexers is like defining Properties
? Elaboration of properties. with two differences –
Indexer takes an index argument.
? Used where one wants to access some
?

The ‘this’ keyword is used as the name of the


class property by index in an array-like ?

indexer as the class itself is used as an array.


manner. E.g. - ListBox
? Useful where a class is a collection for
other objects.

National Centre for Software National Centre for Software


10/26/2002 Technology 35 10/26/2002 Technology 36

6
C# Features C# Features
Indexers Indexers

? E.g. – ? E.g. – Accessing the ? Demo


class MyClass indexer –
{
public object this [int MyClass cls = new
? Indexers are also called Smart Arrays.
idx] MyClass();
{ cls[0] = someObject;
get { // Return
desired data }
set { // Set desired
data }
}
}
National Centre for Software National Centre for Software
10/26/2002 Technology 37 10/26/2002 Technology 38

C# Features C# Features
Interfaces Interfaces

? A C# reference type – similar to a class, ? Can contain Methods, Properties, Indexers


but contains only abstract members. and Events.
? It’s only purpose is to define a set of ? Cannot contain constants, fields, constructors
methods and not to implement them. or any type of static members.
? Java Note – ? All members of interfaces are public by
? Similar to Java interfaces and work in the definition.
same way. ? Interface gives you the ability of multiple
? C++ Note – inheritance.
? Similar to abstract base class which
contains only pure virtual functions.
National Centre for Software National Centre for Software
10/26/2002 Technology 39 10/26/2002 Technology 40

C# Features C# Features
Interfaces Interfaces

E.g. – Interface Definition


?
? Interfaces are contracts between two
interface IExampleInterface
{
disparate pieces of code.
// Example method declaration. ? Therefore, any class that implements an
bool Validate();
// Example property declaration.
interface must define each and every item in
int testProperty { get; } that interface or the code won't compile.
// Example event declaration.
event testEvent Changed;
// Example indexer declaration. ? Demo
string this[i n t index] { get; set; }
}

National Centre for Software National Centre for Software


10/26/2002 Technology 41 10/26/2002 Technology 42

7
C# Features C# Features
Delegates Delegates

? C# specific feature which basically serves the ? Delegate defines a single method without
same purpose as function pointers in C++. implementing it.
? However, delegates are type-safe, secure ? Unlike Interfaces, Delegates refer only to
managed objects.
single methods and are defined at run time.
? Which means that the CLR guarantees that a
? Delegate object will simply delegate the
delegate points to a valid method, which
further means that you get all the benefits of actual processing to the method we pass it.
function pointers without any of the ? Delegates have two main usages in C#
associated dangers, such as an invalid programming: callbacks and event handling.
address or a delegate corrupting the memory
of other objects.

National Centre for Software National Centre for Software


10/26/2002 Technology 43 10/26/2002 Technology 44

C# Features C# Features
Delegates Events

? Callback methods are used when you need to ? Based on Delegates.


pass a function pointer to another function ? Events in C# follow the publish -subscribe
that will then call you back (via the passed design pattern in which a class publishes an
pointer). event that it can "raise" and any number of
? A Callback function is one which one piece of classes can then subscribe to that event.
code defines and another implements. ? Once the event is raised, the runtime takes
care of notifying each subscriber that the
? Demo event has occurred.
? The method called as a result of an event
being raised is defined by a delegate.
National Centre for Software National Centre for Software
10/26/2002 Technology 45 10/26/2002 Technology 46

C# Features C# Features
Events Events

? There are some strict rules concerning a ? The class that wants to use events defines
delegate that's used in this fashion – callback functions as delegates, and the
? First, the delegate must be defined as listening object then implements them.
taking two arguments.
? Second, these arguments always represent ? Demo
two objects: the object that raised the
event (the publisher) and an event
information object.
? Additionally, this second object must be
derived from the .NET Framework's
EventArgs class.
National Centre for Software National Centre for Software
10/26/2002 Technology 47 10/26/2002 Technology 48

8
C# Features
Attributes C# Automatic Memory Management
(Garbage Collection)
? Items of declarative information that can be
declared by the programmer and attached to ?
Every program uses resources of one sort or
elements in your code – classes, methods, another—memory buffers, screen space,
data members or properties. network connections, database resources,
? They can be queried at runtime by anyone and so on.
making use of your class by using reflection.
?
? A number of standard attributes are provided In fact, in an object-oriented environment,
with C#. Most of them allow C# code to work every type identifies some resource available
along with unmanaged code. for your program's use. To use any of these
resources requires that memory be allocated
to represent the type.
National Centre for Software National Centre for Software
10/26/2002 Technology 49 10/26/2002 Technology 50

C# Automatic Memory Management C# Automatic Memory Management


(Garbage Collection) (Garbage Collection)
?
The steps required to access a resource are ? Sources of Programming Errors –
as follows –
1.
? Forget to free memory when it in no longer
Allocate memory for the type that represents the required.
resource.
2.
? Attempting to use memory after having freed it.
Initialize the memory to set the initial state of the ?
resource and to make the resource usable. These two bugs cause resource leaks
3.
Use the resource by accessing the instance (memory consumption) and object corruption
members of the type (repeat as necessary). (destabilization), making your application
4.
Tear down the state of the resource to clean up. perform in unpredictable ways at
5.
Free the memory. unpredictable times.
? Result – Developer must worry about tracking
memory usage and when to free it.
National Centre for Software National Centre for Software
10/26/2002 Technology 51 10/26/2002 Technology 52

C# Automatic Memory Management C# Automatic Memory Management


(Garbage Collection) (Garbage Collection)
? ?
Garbage Collector (GC) completely absolves In the .NET Framework, the developer writes
the developer from tracking memory usage this code in a Close, Dispose, or Finalize
and knowing when to free memory. method.
? ?
GC however doesn't know anything about the The GC can determine when to call this
resource represented by the type in memory method automatically.
? can't know how to perform step four—
tearing down the state of a resource.
?
The developer must write code that knows
how to properly clean up a resource.

National Centre for Software National Centre for Software


10/26/2002 Technology 53 10/26/2002 Technology 54

9
C# Automatic Memory Management C# Automatic Memory Management
(Garbage Collection) (Garbage Collection)
? Resource Allocation – When a process is Managed Heap
?
The Microsoft® .NET Common Language initialized -
?
The CLR reserves a contiguous
Runtime (CLR) requires that all resources region of address space that
be allocated from the managed heap. initially has no storage
? allocated for it.
You never free objects from the managed
?
The address space region is the
heap—objects are automatically freed by managed heap.
the GC when they are no longer needed by ?
The heap also maintains a
the application by following an algorithm. pointer.

National Centre for Software National Centre for Software


10/26/2002 Technology 55 10/26/2002 Technology 56

C# Automatic Memory Management C# Automatic Memory Management


(Garbage Collection) (Garbage Collection)
? Roots: References to ? Managed Heap after
objects on the collection.
managed heap.

National Centre for Software National Centre for Software


10/26/2002 Technology 57 10/26/2002 Technology 58

C# Automatic Memory Management C# Automatic Memory Management


(Garbage Collection) (Garbage Collection)
? Finalise Method – ? E.g. -
?
The garbage collector offers an additional ? public class BaseObj
{
feature that you may want to take advantage public BaseObj() { }
of: finalization. Finalization allows a resource protected override void Finalize()
to gracefully clean up after itself when it is { // Perform resource cleanup code here...

being collected. // Example: Close file/Close network connection


Console.WriteLine("In Finalize.");
?
By using finalization, a resource representing }
a file or network connection is able to clean }

itself up properly when the garbage collector ? When the GC sees that the object is in
decides to free the resource's memory. garbage, and sees that it has a finalise
method, it calls it.

National Centre for Software National Centre for Software


10/26/2002 Technology 59 10/26/2002 Technology 60

10
C# Automatic Memory Management C# Automatic Memory Management
(Garbage Collection) (Garbage Collection)
? In the case of releasing scarce
resources, Microsoft proposes a solution
based on the Dispose design pattern.
? This design pattern recommends that
the object expose a public method,
called something generic like Close or
Dispose,that the user is then instructed
to call when finished using the object.
? It's then up to the class's designer to do
any necessary cleanup in that method.
National Centre for Software National Centre for Software
10/26/2002 Technology 61 10/26/2002 Technology 62

C# Pointers C# Pointers
? Pointers allow direct manipulation of memory. ? Why would you want to bypass the safe
? But, they conflict with the operation of the memory management of C#?
Import some C/C++ code containing pointers.
Garbage Collector (GC).
?

? For some critical block of code which needs to be


? C# lets one run code outside the control of highly efficient, one wants to avoid the overhead
the memory management mechanism. of GC.
? Such code is called Unsafe Code as there’s a ? C# provides for marking blocks of code that
should work outside the control of GC as
possibility that one can introduce all the
unsafe.
problems associated with pointers and direct
memory access. ? One can mark blocks of code or whole
methods as unsafe.

National Centre for Software National Centre for Software


10/26/2002 Technology 63 10/26/2002 Technology 64

C# Pointers C# Pointers
? E.g.- ? SideNote – Unsafe and Unmanaged Code
? Unmanaged Code is code that is not
public class Test
managed by the CLR. E.g. - VB6 executables
{
unsafe public void DoSomething() or standalone VC++ programs without
{ ---- } managed extensions.
? Unsafe Code is managed by the CLR; it just
public void DoSomethingelse() escapes the memory management
{
unsafe { // do something unsafe here }
mechanism (GC) of the C# compiler.
}
}

National Centre for Software National Centre for Software


10/26/2002 Technology 65 10/26/2002 Technology 66

11
C# Exception Handling
C# Exception Handling
? One of the main roles of the CLR –
? Avoid runtime errors through automatic memory ? Exceptions are error conditions that arise
and resource management when using managed when the normal flow of a code path —that is,
code. a series of method calls on the call stack—is
? Catch errors at compile time ( by a strongly typed impractical or imprudent.
system ). ? Most exceptions also involve another
? However, certain errors can be caught only at problem: context.
run time, and therefore a consistent means of ? This is the entire reason for the existence of
dealing with errors must be used across all exception handling: one method determines
the languages that comply with the Common that an exception condition has been reached
Language Specification (CLS). and happens not to be in the correct context
? Error-handling system implemented by the to deal with the error.
CLR —Exception Handling.
National Centre for Software National Centre for Software
10/26/2002 Technology 67 10/26/2002 Technology 68

C# Exception Handling C# Exception Handling


? It signals to the runtime that an error has ? Exception handling consists of only four
occurred. keywords: try, catch, throw, and finally.
? The runtime traverses back up the call stack ? All exceptions that are to be thrown
until it finds a method that can properly deal must be of the type (or derived from)
with the error condition ( I.e. – it searches for System.Exception. In fact, the
exception handler method ). System.Exception class is the base class
? If the runtime can’t find a exception handler of several exception classes that can be
the program will terminate. used in your C# code.

? Demo
National Centre for Software National Centre for Software
10/26/2002 Technology 69 10/26/2002 Technology 70

Miscellaneous

National Centre for Software


10/26/2002 Technology 71

12

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