Agenda What is C# ? ? Some C# FAQs ? C# Features ? Windows Forms ? Web Forms ?
C# - An Introduction - Parag Godkar
10/26/2002
National Centre for Software Technology
1
What is C# ? ?
?
?
National Centre for Software Technology
National Centre for Software Technology
2
Basic Requirements for C# Install Microsoft .Net SDK. Any basic editor – TextPad recommended. ? Windows Forms Programming – Visual Studio.Net ? Web Forms – Visual Studio.Net and IIS. ?
Developed by Anders Hejlsberg and is one of the languages designed for the .NET platform. C# (pronounced C sharp) is a simple, modern, object oriented, and type-safe programming language derived from C and C++. C# aims to combine the high productivity of Visual Basic, the raw power of C++ and the elegance of Java. 10/26/2002
10/26/2002
?
3
10/26/2002
National Centre for Software Technology
4
Agenda What is C# ? Some C# FAQs ? C# Features ? Windows Forms ? Web Forms ? ?
Demo: First Program Keeping in line with the tradition – The Hello World Program
10/26/2002
National Centre for Software Technology
5
10/26/2002
National Centre for Software Technology
6
1
Some C# FAQs ?
Is C# a new version of C++ ? ?
?
?
Some C# FAQs
No, It is a totally new object oriented language built from the ground up to support .Net Framework. The syntax is similar to that of C++.
?
?
How does C# relate to Java ? ?
?
10/26/2002
?
? ?
7
Some C# FAQs ?
?
The .Net Framework SDK includes it. It is not yet distributed individually. Third Parties are free to write their own compilers.
?
?
There is a separate .NET Redistributable runtime (20 MB) available, which can be used to install on the client's machine. Sounds like Java VM ??
National Centre for Software Technology
?
9
Some C# FAQs ?
?
10/26/2002
No for other platforms. But, Microsoft plans to release .Net runtime for other platforms soon. Third Party efforts are on - www.gomono.com.
10/26/2002
National Centre for Software Technology
10
What is C# ? Some C# FAQs ? C# Features ? Windows Forms ? Web Forms ?
Yes, C# and the CLI specifications were submitted by Microsoft to the ECMA (European Computer Manufacturer’s Association) , and they have been ratified as standards.
Why is C# called as C Sharp and not as C Hash ? ?
Yes, for the Windows Platforms – Win 98/ME and Win NT/2000/XP.
Agenda
Is C# an open standard ? ?
8
Is C# Platform Independent ?
?
10/26/2002
National Centre for Software Technology
10/26/2002
Some C# FAQs
How to run C# Programs on Client’s Machine ? ?
Yes, it does. It supports drag, drop and build features of VB.
Where do I get a C# Compiler ? ?
Java Programmers will find it easy to migrate to C#. The concepts are similar to Java. National Centre for Software Technology
Does C# support RAD ( Rapid Application Development ) like VB ?
?
Microsoft knows. National Centre for Software Technology
11
10/26/2002
National Centre for Software Technology
12
2
C# Features
C# Features
Type System
Type System
?
Present Scenario – ?
?
?
Different languages have their own implementation of data types.
?
This difference makes software interoperability very difficult.
? ?
.Net Framework – ?
?
Standard representation and range limit for a data type for all languages supporting .Net Framework. National Centre for Software Technology
10/26/2002
13
C# Features Value types are stored on the stack, and assignment statements between two values variables result in two separate, but identical, copies of the value in memory. ? Reference types are stored on the heap, and an assignment statement between two reference variables results in two references to a single value at one location in memory. ?
National Centre for Software Technology
C# Features ?
-
15
? ? ? ?
? ?
Where they are stored in memory. How they behave in the context of the assignment statements.
10/26/2002
National Centre for Software Technology
National Centre for Software Technology
17
14
Type System
-
Value Types
Allows you to store values in a variable with a certain type. ? It is a reserved space in memory and your program directly manipulates data stored in that space. ? Value types include signed and unsigned. ?
10/26/2002
?
Integral type: sbyte, byte, short, ushort, int, uint, long, ulong and char Floating point types: float and double Decimal type: decimal Bool type: bool Enumeration type: enum
E.g. – enumerators, structures and primitive types
10/26/2002
Value and Reference types differ into two characteristics –
C# Features
Value Types
Value types are further grouped into five ?
?
Type System
Value types Reference types
C# Features
Type System
10/26/2002
In .Net and therefore in C#, types are grouped into two -
?
?
National Centre for Software Technology
Type System
-
16
Reference Types
In C#, all objects are defined as reference types. Although technically it is still a pointer, you are prevented to manipulate it like a pointer. You can forget your pointer maths in C#. They are type -safe pointers meaning that instead of merely being an address, which might or might not point to what you think it does, a reference (when not null) is always guaranteed to point to an object that is of the type specified and that has already been allocated on the heap.
10/26/2002
National Centre for Software Technology
18
3
C# Features ?
?
?
Type System
?
?
National Centre for Software Technology
? ? ?
19
National Centre for Software Technology
C# Features
Boxing and UnBoxing
? ?
int n
All types in C# are objects.
‘obj’
They are objects only when they need to be, thereby avoiding the overhead required if everything actually were an object.
National Centre for Software Technology
?
UnBoxing:
?
E.g.:
?
21
= 4;
object obj = n;
// value type // ‘n’ is boxed to
National Centre for Software Technology
22
C# Features
Boxing and UnBoxing
object and string
?
E.g.: int n = 4; string s = n. ToString() // call Object. ToString ()
?
We need an explicit cast while unboxing as ‘obj’ could be referring to any kind of object and the compiler must verify the type. National Centre for Software Technology
Boxing and UnBoxing
When the compiler finds a value type where it needs a reference type, it creates an object “box” into which it places the value of the value type.
10/26/2002
int n = 4; // value type object obj = n; // create a ‘box’ to hold n int m = (int)obj; // unbox n
10/26/2002
20
Boxing: E.g.:
Conversion of Reference Type to a Value Type.
C# Features
?
ToString() Equals() GetHasCode() GetType()
10/26/2002
UnBoxing:
10/26/2002
Everything is an Object
Everything in the CTS is an object. All objects implicitly derive from a single base class defined as part of the Common Type System (CTS). This base class, called System.Object. It has 4 methods – ?
Conversion of Value Type to a Reference Type.
?
?
?
Boxing: ?
?
C# Features
E.g. classes, arrays, delegates, and interfaces
C# Features
?
Reference Types
C# uses the new keyword to create an object, which is similar to C++. However in C#, the keyword means to instantiate a class and not a specific instruction to allocate memory. The reason behind this is because .Net and C# has a garbage collector, which manages the allocation and release of memory.
10/26/2002
?
-
23
C# provides with two different reference types – object and string. All other classes are based on object even if they don’t claim inheritance from any other class. 10/26/2002
National Centre for Software Technology
24
4
C# Features
C# Features
Classes
Classes
?
?
?
Classes are at the heart of every objectoriented language.
?
?
Used for encapsulation of data and the methods that work on that data. C# borrows a little from C++ and Java and adds some ingenuity to create elegant solutions to old problems.
10/26/2002
National Centre for Software Technology
C++ Note –
?
Java Note – ?
?
25
No semicolon needed at the end of class definition. Unlike Java, C# classes are defined and implemented in the same place.
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.
10/26/2002
National Centre for Software Technology
C# Features
C# Features
Classes
Properties
It doesn't matter to the C# compiler which class has the Main method defined, nor does the class you choose affect the order of compilation. ? The designers of C# included a mechanism by which you can define more than one class with a Main method. Why would you want to do that? One reason is to place test code in your classes.
26
?
10/26/2002
?
?
?
?
National Centre for Software Technology
?
It is bad practice in OOPs to give users of a class public access to Data Members (Class Fields) – for reasons of data integrity.
?
Solution – ‘set and get’ – Accessor Methods.
?
Two Drawbacks – ? ?
27
Code the accessor methods manually. Users have to figure out that they have to use accessor methods.
10/26/2002
National Centre for Software Technology
C# Features
C# Features
Properties
Properties
C# Solution - ‘set and get’ code built into the language and called Properties.
?
Difference to the user – it appears as if they have direct access to the data members (as if the fields are public).
?
?
In reality the compiler maps the call onto set/get built -in get/set methods. The idea of Properties was borrowed from Visual Basic. 10/26/2002
National Centre for Software Technology
29
28
Demo The accessor methods provided by a Property are called Setter and Getter Methods. A property can be readonly by omitting the setter method.
10/26/2002
National Centre for Software Technology
30
5
C# Features
C# Features
Properties
Arrays
?
A property can be decorated with virtual, overide and abstract modifiers, enabling a derived class to inherit and overide properties.
?
?
?
?
National Centre for Software Technology
So defining an Array causes instantiation of System.Array class inheriting all it’s members. Declaring an Array – ?
Because properties provide a generic and intuitive way of accessing data members – object.field – they are sometimes called as Smart Fields.
10/26/2002
In C#, Arrays are objects that have System.Array defined as their base class.
?
31
E.g. – int[] number
An Array is not actually created until you instantiate it just like a class.
National Centre for Software Technology
10/26/2002
C# Features
C# Features
Arrays
Arrays
?
Declaring and Instantiating an Array – ?
?
E.g. – int[] number = new int[7] ---- single dimensional array of 7 integers.
?
32
E.g. – class MyClass { int[] number;
When declaring an array as a member of a class, you need to instantiate the array in two distinct steps because you can’t instantiate an object until runtime.
void SomeMethod() { number = new int[7]; } } ?
10/26/2002
National Centre for Software Technology
33
Demo National Centre for Software Technology
10/26/2002
C# Features
C# Features
Indexers
Indexers
C# specific feature that enables one to programmatically treat objects as though they were arrays. ? Elaboration of properties. ? Used where one wants to access some class property by index in an array-like manner. E.g. - ListBox ? Useful where a class is a collection for other objects. ?
10/26/2002
National Centre for Software Technology
35
?
?
34
Being related to properties, it makes sense to have similar syntax. Defining Indexers is like defining Properties with two differences – ? ?
10/26/2002
Indexer takes an index argument. The ‘this’ keyword is used as the name of the indexer as the class itself is used as an array.
National Centre for Software Technology
36
6
C# Features
C# Features
Indexers
Indexers
?
E.g. –
?
class MyClass { public object this [int idx] { get { // Return desired data } set { // Set desired data } } }
E.g. – Accessing the indexer – MyClass cls = new MyClass(); cls[0] = someObject;
National Centre for Software Technology
10/26/2002
37
?
Demo
?
Indexers are also called Smart Arrays.
10/26/2002
National Centre for Software Technology
C# Features
C# Features
Interfaces
Interfaces
A C# reference type – similar to a class, but contains only abstract members. ? It’s only purpose is to define a set of methods and not to implement them. ? Java Note – ?
?
?
Similar to Java interfaces and work in the same way.
?
?
?
?
C++ Note – ?
Can contain Methods, Properties, Indexers and Events. Cannot contain constants, fields, constructors or any type of static members. All members of interfaces are public by definition. Interface gives you the ability of multiple inheritance.
Similar to abstract base class which contains only pure virtual functions. National Centre for Software Technology
10/26/2002
39
10/26/2002
National Centre for Software Technology
C# Features
C# Features
Interfaces
Interfaces
?
38
E.g. – Interface Definition
?
interface IExampleInterface { // Example method declaration. bool Validate();
?
// Example property declaration. int testProperty { get; } // Example event declaration. event testEvent Changed; ?
// Example indexer declaration. string this[i n t index] { get; set; }
40
Interfaces are contracts between two disparate pieces of code. Therefore, any class that implements an interface must define each and every item in that interface or the code won't compile. Demo
}
10/26/2002
National Centre for Software Technology
41
10/26/2002
National Centre for Software Technology
42
7
C# Features
C# Features
Delegates
Delegates
?
?
?
C# specific feature which basically serves the same purpose as function pointers in C++. However, delegates are type-safe, secure managed objects. Which means that the CLR guarantees that a delegate points to a valid method, which further means that you get all the benefits of function pointers without any of the associated dangers, such as an invalid address or a delegate corrupting the memory of other objects. National Centre for Software Technology
10/26/2002
43
?
?
?
?
Delegate defines a single method without implementing it. Unlike Interfaces, Delegates refer only to single methods and are defined at run time. Delegate object will simply delegate the actual processing to the method we pass it. Delegates have two main usages in C# programming: callbacks and event handling.
10/26/2002
National Centre for Software Technology
C# Features
C# Features
Delegates
Events
?
?
?
Callback methods are used when you need to pass a function pointer to another function that will then call you back (via the passed pointer). A Callback function is one which one piece of code defines and another implements.
? ?
?
Demo ?
National Centre for Software Technology
10/26/2002
45
Based on Delegates. Events in C# follow the publish -subscribe design pattern in which a class publishes an event that it can "raise" and any number of classes can then subscribe to that event. Once the event is raised, the runtime takes care of notifying each subscriber that the event has occurred. The method called as a result of an event being raised is defined by a delegate.
10/26/2002
National Centre for Software Technology
C# Features
C# Features
Events
Events
?
There are some strict rules concerning a delegate that's used in this fashion – ?
?
?
10/26/2002
First, the delegate must be defined as taking two arguments. Second, these arguments always represent 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 Technology
47
?
?
44
46
The class that wants to use events defines callback functions as delegates, and the listening object then implements them. Demo
10/26/2002
National Centre for Software Technology
48
8
C# Features Attributes ?
?
?
C# Automatic Memory Management
Items of declarative information that can be declared by the programmer and attached to elements in your code – classes, methods, data members or properties.
A number of standard attributes are provided with C#. Most of them allow C# code to work along with unmanaged code.
National Centre for Software Technology
4. 5.
In fact, in an object-oriented environment, every type identifies some resource available for your program's use. To use any of these resources requires that memory be allocated to represent the type. 10/26/2002
?
?
?
?
10/26/2002
51
C# Automatic Memory Management
(Garbage Collection) ? Garbage Collector (GC) completely absolves the developer from tracking memory usage and knowing when to free memory. ?
GC however doesn't know anything about the resource represented by the type in memory ? 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.
10/26/2002
National Centre for Software Technology
50
Sources of Programming Errors – ?
Allocate memory for the type that represents the resource. Initialize the memory to set the initial state of the resource and to make the resource usable. Use the resource by accessing the instance members of the type (repeat as necessary). Tear down the state of the resource to clean up. Free the memory. National Centre for Software Technology
National Centre for Software Technology
(Garbage Collection)
The steps required to access a resource are as follows –
3.
?
C# Automatic Memory Management
(Garbage Collection)
2.
Every program uses resources of one sort or another—memory buffers, screen space, network connections, database resources, and so on.
49
C# Automatic Memory Management
1.
?
They can be queried at runtime by anyone making use of your class by using reflection.
10/26/2002
?
(Garbage Collection)
53
Forget to free memory when it in no longer required. Attempting to use memory after having freed it.
These two bugs cause resource leaks (memory consumption) and object corruption (destabilization), making your application perform in unpredictable ways at unpredictable times. Result – Developer must worry about tracking memory usage and when to free it. 10/26/2002
National Centre for Software Technology
52
C# Automatic Memory Management
(Garbage Collection) ? In the .NET Framework, the developer writes this code in a Close, Dispose, or Finalize method. ?
The GC can determine when to call this method automatically.
10/26/2002
National Centre for Software Technology
54
9
C# Automatic Memory Management
C# Automatic Memory Management
(Garbage Collection) ?
Resource Allocation – ?
?
10/26/2002
The Microsoft® .NET Common Language Runtime (CLR) requires that all resources be allocated from the managed heap. You never free objects from the managed heap—objects are automatically freed by the GC when they are no longer needed by the application by following an algorithm.
National Centre for Software Technology
55
C# Automatic Memory Management
National Centre for Software Technology
?
The CLR reserves a contiguous region of address space that initially has no storage allocated for it.
?
The address space region is the managed heap. The heap also maintains a pointer.
?
10/26/2002
Managed Heap
National Centre for Software Technology
(Garbage Collection) ? Managed Heap after collection.
57
10/26/2002
National Centre for Software Technology
C# Automatic Memory Management
C# Automatic Memory Management
(Garbage Collection) ? Finalise Method – ? The garbage collector offers an additional feature that you may want to take advantage of: finalization. Finalization allows a resource to gracefully clean up after itself when it is being collected. ? By using finalization, a resource representing a file or network connection is able to clean itself up properly when the garbage collector decides to free the resource's memory.
(Garbage Collection) ? E.g. -
10/26/2002
National Centre for Software Technology
56
C# Automatic Memory Management
(Garbage Collection) ? Roots: References to objects on the managed heap.
10/26/2002
(Garbage Collection) When a process is initialized -
59
?
?
58
public class BaseObj { public BaseObj() { } protected override void Finalize() { // Perform resource cleanup code here... // Example: Close file/Close network connection Console.WriteLine("In Finalize."); } }
When the GC sees that the object is in garbage, and sees that it has a finalise method, it calls it.
10/26/2002
National Centre for Software 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 Technology
10/26/2002
61
C# Pointers ? ?
?
?
?
62
Why would you want to bypass the safe memory management of C#? ? ?
C# lets one run code outside the control of the memory management mechanism. Such code is called Unsafe Code as there’s a possibility that one can introduce all the problems associated with pointers and direct memory access. National Centre for Software Technology
National Centre for Software Technology
C# Pointers
Pointers allow direct manipulation of memory. But, they conflict with the operation of the Garbage Collector (GC).
10/26/2002
63
C# Pointers ?
10/26/2002
?
?
Import some C/C++ code containing pointers. For some critical block of code which needs to be highly efficient, one wants to avoid the overhead of GC.
C# provides for marking blocks of code that should work outside the control of GC as unsafe. One can mark blocks of code or whole methods as unsafe.
10/26/2002
National Centre for Software Technology
64
C# Pointers
E.g.-
? ?
public class Test { unsafe public void DoSomething() { ---- }
?
public void DoSomethingelse() { unsafe { // do something unsafe here } }
SideNote – Unsafe and Unmanaged Code Unmanaged Code is code that is not managed by the CLR. E.g. - VB6 executables or standalone VC++ programs without managed extensions. Unsafe Code is managed by the CLR; it just escapes the memory management mechanism (GC) of the C# compiler.
}
10/26/2002
National Centre for Software Technology
65
10/26/2002
National Centre for Software Technology
66
11
C# Exception Handling
C# Exception Handling ?
One of the main roles of the CLR – ?
?
?
?
Avoid runtime errors through automatic memory and resource management when using managed code. Catch errors at compile time ( by a strongly typed system ).
?
However, certain errors can be caught only at run time, and therefore a consistent means of dealing with errors must be used across all the languages that comply with the Common Language Specification (CLS). Error-handling system implemented by the CLR —Exception Handling. National Centre for Software
10/26/2002
Technology
67
C# Exception Handling ?
?
?
?
?
Exceptions are error conditions that arise when the normal flow of a code path —that is, a series of method calls on the call stack—is impractical or imprudent. Most exceptions also involve another problem: context. This is the entire reason for the existence of exception handling: one method determines that an exception condition has been reached and happens not to be in the correct context to deal with the error. 10/26/2002
?
The runtime traverses back up the call stack until it finds a method that can properly deal with the error condition ( I.e. – it searches for exception handler method ).
?
If the runtime can’t find a exception handler the program will terminate. ?
10/26/2002
68
C# Exception Handling
It signals to the runtime that an error has occurred.
National Centre for Software Technology
National Centre for Software Technology
69
Exception handling consists of only four keywords: try, catch, throw, and finally.
All exceptions that are to be thrown must be of the type (or derived from) System.Exception. In fact, the System.Exception class is the base class of several exception classes that can be used in your C# code. Demo
10/26/2002
National Centre for Software Technology
70
Miscellaneous
10/26/2002
National Centre for Software Technology
71
12