Introduction To C#: Anders Hejlsberg Distinguished Engineer Developer Division Microsoft Corporation
Introduction To C#: Anders Hejlsberg Distinguished Engineer Developer Division Microsoft Corporation
The first component oriented language in the C/C++ family Everything really is an object Next generation robust and durable software Preservation of investment
C# is the first component oriented language in the C/C++ family Component concepts are first class:
Properties, methods, events Design-time and run-time attributes Integrated documentation using XML
No header files, IDL, etc. Can be embedded in web pages
Traditional views
C++, Java: Primitive types are magic and do not interoperate with objects Smalltalk, Lisp: Primitive types are objects, but at great performance cost Deep simplicity throughout system New primitive types: Decimal, SQL Collections, etc., work for all types
Garbage collection
Exceptions
Type-safety
Versioning
C++ heritage
Namespaces, enums, unsigned types, pointers (in unsafe code), etc. No unnecessary sacrifices What software is increasingly about MS C# implementation talks to XML, SOAP, COM, DLLs, and any .NET language Short learning curve Increased productivity
Interoperability
Hello World
using System; class Hello { static void Main() { Console.WriteLine("Hello world"); } }
C# Program Structure
Namespaces
Contain types and other namespaces Classes, structs, interfaces, enums, and delegates Constants, fields, methods, properties, indexers, events, operators, constructors, destructors No header files, code written in-line No declaration order dependence
Type declarations
Members
Organization
C# Program Structure
using System;
namespace System.Collections { public class Stack { Entry top; public void Push(object data) { top = new Entry(top, data); } public object Pop() { if (top == null) throw new InvalidOperationException(); object result = top.data; top = top.next; return result; } } }
Type System
Value types
Directly contain data Cannot be null Contain references to objects May be null
int i = 123; string s = "Hello world";
Reference types
i s
Type System
Value types
Reference types
Predefined Types
C# predefined types
object, string sbyte, short, int, long byte, ushort, uint, ulong char float, double, decimal bool
Classes
Constants, fields, methods, properties, indexers, events, operators, constructors, destructors Static and instance members Nested types public, protected, internal, private
Member access
Structs
Stored in-line, not heap allocated Assignment copies data, not reference No inheritance
Complex, point, rectangle, color int, float, double, etc., are all structs No heap allocation, less GC pressure More efficient use of memory
Benefits
cp
10 20
CPoint
Interfaces
Multiple inheritance Can contain methods, properties, indexers, and events Private interface implementations
interface IDataBound { void Bind(IDataBinder binder); } class EditBox: Control, IDataBound { void IDataBound.Bind(IDataBinder binder) {...} }
Enums
Strongly typed
Delegates
Everything is an object
All types ultimately inherit from object Any piece of data can be stored, transported, and manipulated with no extra work
object
Stream
Hashtable
int
double
MemoryStream
FileStream
Boxing
Allocates box, copies value into it Checks type of box, copies value out
int i = 123; object o = i; int j = (int)o; i o j 123 System.Int32
Unboxing
123
123
Benefits
Eliminates wrapper classes Collection classes work with all types Replaces OLE Automation's Variant
Component Development
Properties
public class Button: Control { private string caption; public string Caption { get { return caption; } set { caption = value; Repaint(); } } }
Indexers
Can be overloaded
public class ListBox: Control { private string[] items; public string this[int index] get { return items[index]; } set { items[index] = value; Repaint(); } } } {
Events
Sourcing
Events
Handling
Attributes
Documentation URL for a class Transaction context for a method XML persistence mapping Add keywords or pragmas to language Use external files, e.g., .IDL, .DEF
Traditional solutions
C# solution: Attributes
Attributes
public class OrderProcessor { [WebMethod] public void SubmitOrder(PurchaseOrder order) {...} } [XmlRoot("Order", Namespace="urn:acme.b2b-schema.v1")] public class PurchaseOrder { [XmlElement("shipTo")] public Address ShipTo; [XmlElement("billTo")] public Address BillTo; [XmlElement("comment")] public string Comment; [XmlElement("items")] public Item[] Items; [XmlAttribute("date")] public DateTime OrderDate; }
Attributes
Attributes can be
Attached to types and members Examined at run-time using reflection Simply a class that inherits from System.Attribute Arguments checked at compile-time XML, Web Services, security, serialization, component model, COM and P/Invoke interop, code configuration
Completely extensible
Type-safe
XML Comments
class XmlElement { /// <summary> /// Returns the attribute with the given name and /// namespace</summary> /// <param name="name"> /// The name of the attribute</param> /// <param name="ns"> /// The namespace of the attribute, or null if /// the attribute has no namespace</param> /// <return> /// The attribute value, or null if the attribute /// does not exist</return> /// <seealso cref="GetAttr(string)"/> /// public string GetAttr(string name, string ns) { ... } }
High C++ fidelity If, while, do require bool condition goto cant jump into blocks Switch statement
foreach statement Checked and unchecked statements Expression statements must do work
void Foo() { i == 1; } // error
foreach Statement
Iteration of arrays
public static void Main(string[] args) { foreach (string s in args) Console.WriteLine(s); }
Parameter Arrays
void printf(string fmt, params object[] args) { foreach (object x in args) { ... } } printf("%s %i %i", str, int1, int2); object[] args = new object[3]; args[0] = str; args[1] = int1; Args[2] = int2; printf("%s %i %i", args);
Operator Overloading
Used in UI library
Operator Overloading
public struct DBInt { public static readonly DBInt Null = new DBInt();
Versioning
C++ and Java produce fragile base classes Users unable to express versioning intent Methods are not virtual by default C# keywords virtual, override and new provide context Can enable (e.g., explicit override) Can encourage (e.g., smart defaults)
Versioning
class Base // version 2 1 { } public virtual void Foo() { Console.WriteLine("Base.Foo"); } }
class Derived: Base // version 2b 1 2a { new public public virtual override virtual void void void Foo() Foo() Foo() {{ { Console.WriteLine("Derived.Foo"); base.Foo(); } Console.WriteLine("Derived.Foo"); } } }
Conditional Compilation
Conditional methods
public class Debug { [Conditional("Debug")] public static void Assert(bool cond, String s) { if (!cond) { throw new AssertionException(s); } } }
Unsafe Code
Low-level code within the box Enables unsafe casts, pointer arithmetic
Declarative pinning
Fixed statement
Basically inline C
unsafe void Foo() { char* buf = stackalloc char[256]; for (char* p = buf; p < buf + 256; p++) *p = 0; ... }
Unsafe Code
class FileStream: Stream { int handle;
public unsafe int Read(byte[] buffer, int index, int count) { int n = 0; fixed (byte* p = buffer) { ReadFile(handle, p + index, count, &n, null); } return n; }
[dllimport("kernel32", SetLastError=true)] static extern unsafe bool ReadFile(int hFile, void* lpBuffer, int nBytesToRead, int* nBytesRead, Overlapped* lpOverlapped);
More Information
http://msdn.microsoft.com/net
http://msdn.microsoft.com/events/pdc
news://msnews.microsoft.com