csharp dev
TRANSCRIPT
C# .NET
2
Agenda
• The .NET Framework and the CLR• Common Type System (CTS) and Common Language
Specification (CLS)• Language Basics of C#• Unique Features of C#
3
Managed and Unmanaged Code
CIL(Common Intermediate Language)
Managed Code (C#, VB.NET, etc.)
.NET Compiler
x86 Machine Code
Unmanaged Code(VB 6, C++, etc.)
Compiler
CLR (Common Language Runtime)
x86 Machine Code
Generated at compile time!
Generated at RUN time!
Depending on the version of the CLR different machine code can be generated.
Managed Code Unmanaged Code
4
The .NET Framework is a development platform
• .NET Framework provides– Choice of several different language compilers– Debugger– Large number of Framework Class Libraries– Several different tools for inspection, security, deployment– Common Language Runtime (CLR) for Windows – Common Language Runtime for lightweight devices
5
Why a Runtime?
• MTS and COM+ were just better runtimes for COM objects– better threading support– better security– better transaction support
• .NET is just another runtime– With a whole lot more added value– Much more open/exposed architecture– Huge class library– Better threading story– Better memory management story– Better deployment story – xcopy deployments– Better configuration story - No registry dependencies– Better security story – Based on components not process/threads
6
Common Language Runtime
• CLR is your new Runtime– In a way it’s like a new Operating System– It deals with memory layout– Provides your type system– Provides an additional layer of security– Provides a threading model– Provides ability to run code on other platforms
• Knowing how the CLR works is they key to building applications with .NET
7
Run on Any Platform
• Today mainly Windows machines• Handheld devices are also supported• Rotor – Open Source Project for Linux and other platforms
Server Computer
Common Language Runtime (CLR)
Operating System
Hardware
Your code
Framework Class Libraries
Desktop Computer
Common Language Runtime (CLR)
Operating System
Hardware
Your code
Framework Class Libraries
Handheld device
Compact Framework (CF)
Operating System
Hardware
Your code
Framework Class Libraries
Your code
Windows Server 2003
Windows XP Professional CF-compatible device
8
Talk to Any Platform
• Running code on any platform may be desirable• Running code that can talk to any platform is often more desirable
Linux Server
IBM Mainframe
Oracle DB
Windows Server
.NET Web Service Client
9
Platforms That Support .NET Framework
• Client-side Windows platforms– Windows XP– Windows 2000– Windows NT– Windows 98/Windows ME
• Server-side Windows platforms (ASP.NET)– Windows Server 2003– Windows 2000 Server– Windows XP – for development purposes
• ASP.NET Helpful Install Utility– aspnet_regiis.exe /i will install ASP.NET on a machine after
VS.NET was installed
10
Common Type System - CTS
• The CLR defines the type system, CTS• All .NET languages map into the CTS• CLR types defined under the System Namespace• All .NET languages provide their own keywords that map to the
underlying CTS types– C# int keyword == System.Int32– VB.NET integer keyword = System.Int32
11
Common Type System (CTS)
• CLR programming model is based on the CTS– CTS provides backbone for the CLR– CTS defines a core set of system types– CTS defines set of object-oriented programming features– CTS defines rules for creating user-defined types– all managed languages must map to the CTS
12
Core CTS types• System.Object is root of type system
– All types derive from Object– Some types treated special with regard to memory layout
(ValueTypes)
St r i ng Ar r ay Val ueType Except i on Del egat e Cl ass1
Mul t i castDel egat e Cl ass2
Cl ass3
Obj ect
Enum1
St r uct ur e1EnumPr i mi t i ve t ypes
Bool ean
Byt e
I nt 16
I nt 32
I nt 64
Char
Si ngl e
Doubl e
Deci mal
Dat eTi me
System-defined types
User-defined types
Del egat e1
Ti meSpan
Gui d
13
Common Language Specification (CLS)
• Ensures language interoperability• Defines a subset of the CTS• Most of the Framework Class Libraries are CLS compliant• Cannot overload based on return type• Unsigned integral types are not allowed on public methods• Can use the CLSCompliantAttribute to enforce checks
14
Boolean
character
integer
floating point
string
C# Types – extend CLS Types
• Comprehensive set of simple types available
Type Description Special format for literalsbool Boolean true false
char 16 bit Unicode character 'A' '\x0041' '\u0041'sbyte 8 bit signed integer none
byte 8 bit unsigned integer none
short 16 bit signed integer none
ushort 16 bit unsigned integer none
int 32 bit signed integer none
uint 32 bit unsigned integer U suffixlong 64 bit signed integer L or l suffixulong 64 bit unsigned integer U/u and L/l suffixfloat 32 bit floating point F or f suffixdouble 64 bit floating point no suffixdecimal 128 bit high precision M or m suffixstring character sequence "hello"
15
Agenda
The .NET Framework and the CLR Common Type System (CTS) and Common Language
Specification (CLS)• Language Basics of C#• Unique Features of C#
16
C# and VB.NET – not as different as you might think
• Both have:– Support structured exception handling– Support for Interfaces– Support for Inheritance– Support for virtual functions– Support for static functions– Support for method overloading– Support for constructors/destructors– Support for indexers– Support FCL
17
Class Basics
class Client{
static void Main(string[] args){
Human h = new Human();h.Age = 21;h.Name = "Rian Brandell";
}}
public class Human{public int Age;public string Name;public void Speak(){
Console.WriteLine(“Name:{0} Age:{1}",Name,Age);}
}
Simple class with public fields for properties
Client code working with Human classes
18
Propertiespublic class Human{
private int m_Age;public int Age{
set{
if (value > 0){
m_Age = value;}else{ throw new ArgumentOutOfRangeException("Age invalid");}
}get{return m_Age;}
}}
A better way of exposing data members, through a public property and private field for storage
19
Interfaces
• Interfaces are an explicit kind of type in the CLR– Express what is common across classes– Allow classes to share a common design– Include sufficient type information to program against, but not
enough to instantiate– Members may include methods, properties, indexers, and events– Cannot include implementation details or fields– Concrete type must supply all implementation details
20
Implementing and using interfacesusing System;interface ICowboy {
void Draw();string Name { get; }object this[int n] { get; }
}
class Rancher : ICowboy {
public void Draw() { Console.WriteLine("Bang!"); }public string Name { get { return("Tex"); } }public object this[int n] { get { return(...); } }
}
class Wrangler : ICowboy {
public void Draw() { Console.WriteLine("Bang!"); }public string Name { get { return("Woody"); } }public object this[int n] { get { return(...); } }
}
ICowboy cb = new Rancher();cb.Draw();Console.WriteLine(cb.Name);cb = new Wrangler();cb.Draw();Console.WriteLine(cb.Name);
Using the interfaces
Declaring and implementing the interfaces
21
Type compatibility and navigation
• C# supports typical type compatibility– Types may implement multiple interfaces– A class must declare which interface it supports
• The CLR supports explicit runtime type navigation– An object is type-compatible with interface X if and only if the
object's class supports interface X– C# is, as, and typecast operators support explicit run-time type
navigation
22
Using Type Navigation Operatorsinterface ICowboy {}interface IArtist {}class Tex : ICowboy {}class LaRoche : IArtist {}
// What happens if DrawAndPaint is passed// a Tex or LaRoche instance?//void DrawAndPaint( object o ) {
// InvalidCastException on failure:IArtist a = (IArtist)o;a.Paint();
// False on failure:bool IsArmed = o is ICowboy;
// Null reference on failure:ICowboy cb = o as ICowboy;if( cb != null ) {cb.Draw();}
}
Using explicit cast, is and as operations to perform type navigation
23
Explicit interface implementation
interface ICowboy { void Draw(); }interface IArtist { void Draw(); }
class LaTex : ICowboy, IArtist{
void ICowboy.Draw() { Console.WriteLine("Bang!"); }void IArtist.Draw() { Console.WriteLine("Brush, brush"); }
}
LaTex starvingDrifter = new LaTex();starvingDrifter.Draw(); // Compiler error - no public Draw()ICowboy cb = starvingDrifter;cb.Draw(); // Bang!IArtist a = starvingDrifter;a.Draw(); // Brush, brush
Implementation is not marked public so the only way to get to the implementation is through the interface
24
Base classes
• Every type has at most one base type– System.Object and interfaces have no base type– System.Enum for enums, System.Array for arrays– Base type for classes defaults to System.Object if not explicitly
specified– sealed class modifier prevents use as a base type– abstract class modifier mandates derivation
25
public class MyClassName : BaseImpl, Itf1, Itf2{ // member definitions go here}
List of supported interfaces
Name of base type
Specifying a base class in C#
26
Base/derived construction
• Constructors and base types have "issues"– Base type constructors not part of derived type's signature– Base type constructors must be called from derived constructors
using C++-like syntax– Overloaded constructor on self can be called using C++-like
syntax– Base type's constructor executes using the most-derived type (like
Java, not C++)– Waterfall construction model for C# allows derived members to be
accessed prior to initialization
27
Base types and constructors
interface IPerson {...}interface ICowboy {...}
public class PersonImpl : IPerson{
public PersonImpl(string name) {...}public PersonImpl(string name, int age) {...}
}
public class Cowboy : PersonImpl, ICowboy{
public Cowboy(string n, int a ) : base(n, a) {...}public Cowboy(string n) : base(n) {...}public Cowboy() : this("Tex", 34) {}public void Draw() {...}
}
Chain call to base types constructor
28
public class Base { public int x = a(); public Base() { b(); }}
public class D1 : Base { public int y = c(); public D1() { d(); }}
public class D2 : D1 { public int z = e(); public D2() { f(); }}
public class D3 : D2 { public int w = g(); public D3() { h(); }}
D3..ctor()
g()
D2..ctor
h()
e()
D1..ctor
f()
c()
Base..ctor()
d()
a()
b()
Derivation and constructor flow of control
29
sealed
virtual
abstract
C# Syntax
From the perspective of a base class designer
Meaning
Method may be replaced by derived class.
Method must be replaced by a derived class (or redeclared abstract).
Method may not be replaced by a derived class.
override
new
C# Syntax
From the perspective of a derived class designer
Meaning
Method replaces a virtual/abstract/override method in the base with its ownimplementation, and is still overridable by further derived types.
Method is unrelated to a similarly defined method in the base class. Typicallyused to deal with a change to a base class that creates a collision where onedidn't exist before, and where it's not practical to just choose a different methodname.
C# method dispatching modifiers
30
Using method dispatching modifiersabstract class Base {
public void a() {} // statically bound, cannot overridepublic virtual void b() {} // may be overriddenpublic abstract void c(); // must override or redeclare abstractpublic virtual void d() {} // may be overridden
}
class Derived : Base {
public override void a() {} // illegal: Base.a not overridablepublic override void b() {} // legal: Base.b override allowedpublic override void c() {} // legal: Base.c override requiredpublic new void d() {} // unrelated to Base.d, not overridable
}
class MoreDerived : Derived {
public override void c() {} // legal: Derived.c still overridable}
31
sealed override
new virtual
C# Syntax
Method modifer combinations
Meaning
This method replaces a virtual/abstract/override method in the base with its ownimplementation, and terminates the overridability of this method as far as furtherderived types are concerned.
This method is unrelated to a similarly defined method in the base class andgets a new slot in the associated virtual method dispatching table for this class.Further derived types may choose to override this method.
new abstractThis method is unrelated to a similarly defined method in the base class andgets a new slot in the associated virtual method dispatching table for this class.Further derived types must to override this method.
Combining method dispatching modifiers
32
Combining method modifiersabstract class Base {
public void a() {} // statically bound, cannot overridepublic virtual void b() {} // may be overriddenpublic abstract void c(); // must override or redeclare abstractpublic virtual void d() {} // may be overridden
}
abstract class Derived : Base {
public sealed override void b() {} // terminal override of Base.bpublic new virtual void d() {} // unrelated to Base.d, overridable
}
class MoreDerived : Derived {
public override void b() {} // illegal: Derived.b sealedpublic override void c() {} // overrides Base.cpublic override void d() {} // overrides Derived.d
}
33
Destructors
• Implemented by defining a method via ~ClassName, like C++• Not called directly by your code• Called by the Garbage Collector when needed• Often desirable to have cleanup code run before GC runs
– Implement IDisposable interface– Called by client when done using object
34
Destructors and IDisposableusing System;class Class1{
static void Main(string[] args){
Widget wg = new Widget();Console.WriteLine(wg.ToString());wg.Dispose(); //specific call to cleanupwg = null; //let go of reference and wait for GCConsole.ReadLine();
}}public class Widget : IDisposable{
~Widget(){
//cleanup code called by GC}public void Dispose(){
//perform cleanup}
}
Destructor called by GC
Dispose called by client!
35
Agenda
The .NET Framework and the CLR Common Type System (CTS) and Common Language
Specification (CLS) Language Basics of C#• Unique Features of C#
36
Culturally Very Different ;-)
• C# is much a more disciplined/strict language than VB.NET– Case sensitive– No “Option Explicit Off” for variable declarations– No “Option Strict Off” for strict type checking– Required to initialize variables before use– Targeted towards C++ and Java developer– Not hard to switch too if coming from VB though
37
Unique C# Features
• Native support for Unsigned integral types• Operator overloading• Using statement
– Ensures IDisposable.Dispose is called• Unsafe code blocks
– Mainly used to support API’s that require pointers• Documentation Comments
– Used to generate XML or HTML documentation• Strict type checking is on and can’t be turned off
– VB.NET has Option Strict on/off with Off being the default
38
Operator Overloadingusing System;class Client{
static void Main(string[] args){Point p1 = new Point();p1.x = 10; p1.y=10;
Point p2 = new Point();p2.x = 10; p2.y=10;
Point p3 = p1 + p2;Console.WriteLine("p3.x:{0} p3.y:{1}",p3.x,p3.y);
}}class Point{
public int x;public int y;public static Point operator+(Point p1, Point p2){
Point p = new Point();p.x = p1.x + p2.x;p.y = p1.y + p2.y;return p;
}}
Use the operator keyword and whichever operator you wish to overload
39
Using Statementusing System;
class Class1{
static void Main(string[] args){
using(DataBaseManager dbm = new DataBaseManager()){
//use dbm
}//Dispose method of dbm called automatically!}
}
public class DataBaseManager : IDisposable{
void IDisposable.Dispose(){
//database cleanup code}
}
Using statement causes automatic call to Dispose to be generated at compile time
40
Unsafe Code Blocks
[DllImport("kernel32", SetLastError=true)]static extern unsafe bool ReadFile(int hFile,
void* lpBuffer, int nBytesToRead,int* nBytesRead, int overlapped);
public unsafe int Read(byte[] buffer, int index, int count) {
int n = 0;fixed (byte* p = buffer) {
ReadFile(handle, p + index, count, &n, 0);}return n;
}
• Must set compiler option in project properties– Project->Properties->Configuration Properties->Build->Allow
Unsafe Code blocks – set to true
Marked as Unsafe due to pointers
Marked fixed to keep object from moving when GC runs
41
Documentation Comments
• Just type “///” above a method and VS.NET does the rest!• Project->Properties->Configuration Properties->Build->XML
Documentation Path• Tools->Build Comment Web Pages…• Generates XML and HTML page for viewing
/// <summary>/// Class for managing checking account/// </summary>public class Checking{
/// <summary>/// Called to make a deposit/// </summary>/// <param name="amount"></param>/// <returns></returns>public int MakeDeposit(int amount){
}}
42
Documentation Comments-Output
43
Summary
The .NET Framework and the CLR Common Type System (CTS) and Common Language
Specification (CLS) Language Basics of C# Unique Features of C#