Introduction to C #
Prerequisites This module assumes that you understand the fundamentals of Programming Variables, statements, functions, loops, etc. Object-oriented programming  Classes, inheritance, polymorphism,  members, etc. C++ or Java
Learning Objectives C# design goals Fundamentals of the C# language Types, program structure, statements, operators Be able to begin writing and debugging C# programs Using the .NET Framework SDK Using Visual Studio.NET Be able to write individual C# methods
Agenda Hello World Design Goals of C# Types Program Structure Statements Operators Using Visual Studio.NET Using the .NET Framework SDK
Hello World using System; class Hello { static void Main( ) { Console.WriteLine("Hello world"); Console.ReadLine();  // Hit enter to finish } }
Agenda Hello World Design Goals of C# Types Program Structure Statements Operators Using Visual Studio.NET Using the .NET Framework SDK
Design Goals of C# The Big Ideas Component-orientation Everything is an object Robust and durable software Preserving your investment
Design Goals of C#  Component-Orientation C# is the first “Component-Oriented” language in the C/C++ family What is a component? An independent module of reuse and deployment Coarser-grained than objects  (objects are language-level constructs) Includes multiple classes Often language-independent In general, component writer and user don’t know each other, don’t work for the same company, and don’t use the same language
Design Goals of C#  Component-Orientation Component concepts are first class Properties, methods, events Design-time and run-time attributes Integrated documentation using XML Enables “one-stop programming” No header files, IDL, etc. Can be embedded in ASP pages
Design Goals of C#  Everything is an Object Traditional views C++, Java™:  Primitive types are “magic” and do not interoperate with objects Smalltalk, Lisp:  Primitive types are objects, but at some performance cost C# unifies with no performance cost Deep simplicity throughout system Improved extensibility and reusability New primitive types:  Decimal, SQL… Collections, etc., work for all types
Design Goals of C#  Robust and Durable Software Garbage collection No memory leaks and stray pointers Exceptions Type-safety No uninitialized variables, no unsafe casts Versioning Avoid common errors E.g. if (x = y) ... One-stop programming Fewer moving parts
Design Goals of C#  Preserving Your Investment C++ Heritage Namespaces, pointers (in unsafe code),  unsigned types, etc. Some changes, but no unnecessary sacrifices Interoperability What software is increasingly about C# talks to XML, SOAP, COM, DLLs, and any  .NET Framework language Increased productivity Short learning curve Millions of lines of C# code in .NET
Agenda Hello World Design Goals of C# Types Program Structure Statements Operators Using Visual Studio.NET Using the .NET Framework SDK
Types Overview A C# program is a collection of types Classes, structs, enums, interfaces, delegates C# provides a set of predefined types E.g.  int ,  byte ,  char ,  string ,  object , … You can create your own types All data and code is defined within  a type No global variables, no global functions
Types Overview Types contain: Data members Fields, constants, arrays Events Function members  Methods, operators, constructors, destructors Properties, indexers Other types Classes, structs, enums, interfaces, delegates
Types Overview Types can be instantiated… …and then used: call methods,  get and set properties, etc. Can convert from one type to another Implicitly and explicitly Types are organized Namespaces, files, assemblies There are two categories of types: value and reference Types are arranged in a hierarchy
Types  Unified Type System Value types Directly contain data Cannot be null Reference types Contain references to objects May be null int i = 123; string s = "Hello world"; 123 i s "Hello world"
Types  Unified Type System Value types Primitives int i; float x; Enums enum State { Off, On } Structs struct Point {int x,y;} Reference types Root object String string Classes class Foo: Bar, IFoo {...} Interfaces interface IFoo: IBar {...} Arrays string[] a = new string[10]; Delegates delegate void Empty();
Types  Unified Type System Yes No Aliasing (in a scope) May be null Always has value Nullability Copy reference Copy data Assignment means null 0 Default value Heap Stack, member Allocated on Memory location Actual value Variable holds Reference (Class) Value  (Struct)
Types  Unified Type System Benefits of value types No heap allocation, less GC pressure More efficient use of memory Less reference indirection Unified type system No primitive/object dichotomy
Types Conversions Implicit conversions  Occur automatically Guaranteed to succeed No information (precision) loss Explicit conversions  Require a cast May not succeed Information (precision) might be lost Both implicit and explicit conversions can be user-defined
Types Conversions int x = 123456; long y = x; // implicit short z = (short)x; // explicit double d = 1.2345678901234; float f = (float)d; // explicit long l = (long)d; // explicit
Types Unified Type System Everything is an object All types ultimately inherit from object Any piece of data can be stored, transported, and manipulated with no extra work
Types Unified Type System Polymorphism The ability to perform an operation on an object without knowing the precise type of the object void Poly(object o) { Console.WriteLine(o.ToString());  } Poly(42); Poly(“abcd”); Poly(12.345678901234m); Poly(new Point(23,45));
Types Unified Type System Question: How can we treat value and reference types polymorphically? How does an int (value type) get converted into an object (reference type)? Answer: Boxing! Only value types get boxed Reference types do not get boxed
Types Unified Type System Boxing Copies a value type into a reference type ( object ) Each value type has corresponding “hidden” reference type Note that a reference-type copy is made of the  value type Value types are never aliased Value type is converted implicitly to  object , a reference type Essentially an “up cast”
Types Unified Type System Unboxing Inverse operation of boxing Copies the value out of the box Copies from reference type to value type Requires an explicit conversion May not succeed (like all explicit conversions) Essentially a “down cast”
Types Unified Type System Boxing and unboxing int i = 123; object o = i; int j = (int)o; 123 i o 123 j 123 System.Int32
Types Unified Type System Benefits of boxing Enables polymorphism across all types Collection classes work with all types Eliminates need for wrapper classes Replaces OLE Automation's Variant Lots of examples in .NET Framework Hashtable t = new Hashtable(); t.Add(0, "zero"); t.Add(1, "one"); t.Add(2, "two"); string s = string.Format( "Your total was {0} on {1}",  total, date);
Types Unified Type System Disadvantages of boxing Performance cost The need for boxing will decrease when the CLR supports generics (similar to C++ templates)
Types Predefined Types Value Integral types Floating point types decimal bool char Reference object string
Predefined Types Value Types All are predefined structs bool Logical char Character float, double, decimal Floating point byte, ushort, uint, ulong Unsigned sbyte, short, int, long Signed
Predefined Types Integral Types No 2 System.UInt16 ushort No 4 System.UInt32 uint No 1 System.Byte byte Yes 8 System.Int64 long 8 4 2 1 Size (bytes) No System.UInt64 ulong Yes System.Int32 int Yes System.Int16 short Yes System.Sbyte sbyte Signed? System Type C# Type
Predefined Types Floating Point Types Follows IEEE 754 specification Supports ± 0, ± Infinity, NaN  8 4 Size (bytes) System.Double double System.Single float System Type C# Type
Predefined Types decimal 128 bits Essentially a 96 bit value scaled by a  power of 10 Decimal values represented precisely Doesn’t support signed zeros, infinities  or NaN 16 Size (bytes) System.Decimal decimal System Type C# Type
Predefined Types decimal All integer types can be implicitly converted to a decimal type Conversions between decimal and floating types require explicit conversion due to possible loss of precision s * m * 10e s = 1 or –1 0    m    296 -28    e    0
Predefined Types Integral Literals Integer literals can be expressed as decimal  or hexadecimal U or u: uint or ulong L or l: long or ulong UL or ul: ulong 123  // Decimal 0x7B  // Hexadecimal 123U  // Unsigned 123ul  // Unsigned long 123L  // Long
Predefined Types Real Literals F or f: float D or d: double M or m: decimal 123f  // Float 123D  // Double 123.456m  // Decimal 1.23e2f  // Float 12.3E1M  // Decimal
Predefined Types bool Represents logical values Literal values are true and false Cannot use 1 and 0 as boolean values No standard conversion between other types  and bool 1 (2 for arrays) Size (bytes) System.Boolean bool System Type C# Type
Predefined Types char Represents a Unicode character Literals ‘A’ // Simple character ‘\u0041’ // Unicode ‘\x0041’ // Unsigned short hexadecimal ‘\n’ // Escape sequence character 2 Size (bytes) System.Char Char System Type C# Type
Predefined Types char Escape sequence characters (partial list) 0x000A New line \n 0x0000 Null \0 0x005C Backslash \\ 0x0022 Double quote \” 0x000D Carriage return \r 0x0027 Single quote \’ 0x0009 Value Tab \t Meaning Char
Predefined Types Reference Types string Character string object Root type
Predefined Types object Root of object hierarchy Storage (book keeping) overhead 0 bytes for value types 8 bytes for reference types An actual reference (not the object)  uses 4 bytes 0/8 overhead Size (bytes) System.Object object System Type C# Type
Predefined Types object  Public Methods public bool Equals(object) protected void Finalize() public int GetHashCode() public System.Type GetType() protected object MemberwiseClone() public void Object() public string ToString()
Predefined Types string An immutable sequence of Unicode characters Reference type Special syntax for literals string s = “I am a string”; 20 minimum Size (bytes) System.String String System Type C# Type
Predefined Types string Normally have to use escape characters Verbatim string literals Most escape sequences ignored Except for “”  Verbatim literals can be multi-line string s1= “\\\\server\\fileshare\\filename.cs”; string s2 = @“\\server\fileshare\filename.cs”;
Types  User-defined Types User-defined types enum Enumerations interface Interface delegate Function pointer struct Value type class Reference type int[], string[] Arrays
Types  Enums An enum defines a type name for a related group of symbolic constants Choices must be known at compile-time Strongly typed No implicit conversions to/from int Can be explicitly converted Operators: +, -, ++, --, &, |, ^, ~, … Can specify underlying type byte, sbyte, short, ushort, int, uint, long, ulong
Types  Enums enum Color: byte { Red  = 1, Green = 2, Blue  = 4, Black = 0, White = Red | Green | Blue } Color c = Color.Black; Console.WriteLine(c); // 0 Console.WriteLine(c.Format()); // Black
Types  Enums All enums derive from  System.Enum Provides methods to  determine underlying type  test if a value is supported  initialize from string constant retrieve all values in enum …
Types  Arrays Arrays allow a group of elements of a specific type to be stored in a contiguous block of memory Arrays are reference types Derived from  System.Array Zero-based Can be multidimensional Arrays know their length(s) and rank Bounds checking
Types  Arrays Declare Allocate Initialize Access and assign Enumerate int[] primes; int[] primes = new int[9]; int[] prime = new int[] {1,2,3,5,7,11,13,17,19};  int[] prime = {1,2,3,5,7,11,13,17,19}; prime2[i] = prime[i]; foreach (int i in prime) Console.WriteLine(i);
Types  Arrays Multidimensional arrays Rectangular int[,] matR = new int[2,3]; Can initialize declaratively int[,] matR =    new int[2,3] { {1,2,3}, {4,5,6} }; Jagged An array of arrays int[][] matJ = new int[2][]; Must initialize procedurally
Types  Interfaces An interface defines a contract Includes methods, properties, indexers, events Any class or struct implementing an interface must support all parts of the contract Interfaces provide polymorphism Many classes and structs may implement  a particular interface Contain no implementation Must be implemented by a class or struct
Types  Classes User-defined reference type Similar to C++, Java classes Single class inheritance Multiple interface inheritance
Types  Classes Members Constants, fields, methods, operators,  constructors, destructors Properties, indexers, events Static and instance members Member access public ,  protected ,  private ,  internal ,  protected   internal Default is  private Instantiated with  new  operator
Types  Structs Similar to classes, but User-defined value type Always inherits from object Ideal for lightweight objects int ,  float ,  double , etc., are all structs User-defined “primitive” types Complex, point, rectangle, color, rational Multiple interface inheritance Same members as class Member access public ,  internal ,  private Instantiated with  new  operator
Types  Classes and Structs struct SPoint { int x, y; ... } class CPoint { int x, y; ... } SPoint sp = new SPoint(10, 20); CPoint cp = new CPoint(10, 20); 10 20 sp cp 10 20 CPoint
Types  Delegates A delegate is a reference type that defines a method signature When instantiated, a delegate holds one or more methods Essentially an object-oriented function pointer Foundation for framework events
Agenda Hello World Design Goals of C# Types Program Structure Statements Operators Using Visual Studio.NET Using the .NET Framework SDK
Program Structure Overview Organizing Types Namespaces References Main Method Syntax
Program Structure Organizing Types Physical organization Types are defined in files Files are compiled into  modules Modules are grouped  into assemblies Assembly Module File Type
Program Structure Organizing Types Types are defined in files A file can contain multiple types Each type is defined in a single file Files are compiled into modules Module is a DLL or EXE A module can contain multiple files Modules are grouped into assemblies Assembly can contain multiple modules Assemblies and modules are often 1:1
Program Structure Organizing Types Types are defined in ONE place “One-stop programming” No header and source files to synchronize Code is written “in-line” Declaration and definition are one and  the same A type must be fully defined in one file Can’t put individual methods in different files No declaration order dependence No forward references required
Program Structure Namespaces Namespaces provide a way to  uniquely identify a type Provides logical organization of types Namespaces can span assemblies Can nest namespaces There is no relationship between namespaces and file structure (unlike Java) The fully qualified name of a type includes all namespaces
Program Structure Namespaces namespace N1 {     // N1 class C1 {   // N1.C1 class C2 {   // N1.C1.C2 }     }     namespace N2 {    // N1.N2 class C2 { // N1.N2.C2     }     }  }
Program Structure Namespaces The using statement lets you use types without typing the fully qualified name Can always use a fully qualified name using N1; C1 a; // The N1. is implicit N1.C1 b; // Fully qualified name C2 c; // Error! C2 is undefined N1.N2.C2 d; // One of the C2 classes C1.C2 e; // The other one
Program Structure Namespaces The  using  statement also lets you create aliases  using C1 = N1.N2.C1; using N2 = N1.N2; C1 a; // Refers to N1.N2.C1 N2.C1 b; // Refers to N1.N2.C1
Program Structure Namespaces Best practice: Put all of your types in a unique namespace Have a namespace for your company, project, product, etc. Look at how the .NET Framework classes are organized
Program Structure References In Visual Studio you specify references  for a project Each reference identifies a specific assembly Passed as reference ( /r  or  /reference )  to the C# compiler csc HelloWorld.cs /reference:System.WinForms.dll
Program Structure Namespaces vs. References Namespaces provide language-level naming shortcuts Don’t have to type a long fully qualified name over and over References specify which assembly to use
Program Structure Main Method Execution begins at the static  Main()  method Can have only one method with one of  the following signatures in an assembly static void Main() static int Main() static void Main(string[] args) static int Main(string[] args)
Program Structure Syntax Identifiers Names for types, methods, fields, etc. Must be whole word – no white space Unicode characters Begins with letter or underscore Case sensitive Must not clash with keyword Unless prefixed with @
Agenda Hello World Design Goals of C# Types Program Structure Statements Operators Using Visual Studio.NET Using the .NET Framework SDK
Statements Overview High C++ fidelity if ,  while ,  do  require  bool  condition goto  can’t jump into blocks switch  statement No fall-through foreach  statement checked  and  unchecked  statements Expression  statements  must do work void Foo() { i == 1;  // error }
Statements Overview Statement lists Block statements Labeled statements Declarations Constants Variables Expression statements checked, unchecked lock using Conditionals if switch Loop Statements while do for foreach Jump Statements break continue goto return throw Exception handling try throw
Statements Syntax Statements are terminated with a  semicolon ( ; ) Just like C, C++ and Java Block statements { ... } don’t need a semicolon
Statements Syntax Comments // Comment a single line, C++ style /* Comment multiple    lines,   C style */
Statements Statement Lists & Block Statements Statement list: one or more statements in sequence Block statement: a statement list delimited by braces  { ... } static void Main() {  F(); G(); {  // Start block H(); ;  // Empty statement I(); }  // End block }
Statements Variables and Constants static void Main() { const float pi = 3.14f; const int r = 123; Console.WriteLine(pi * r * r); int a; int b = 2, c = 3; a = 1; Console.WriteLine(a + b + c); }
Statements Variables and Constants The scope of a variable or constant runs from the point of declaration to the end of  the enclosing block
Statements Variables and Constants Within the scope of a variable or constant it is an error to declare another variable or constant with the same name { int x; { int x; // Error: can’t hide variable x } }
Statements Variables Variables must be assigned a value before they can be used Explicitly or automatically Called definite assignment Automatic assignment occurs for static fields, class instance fields and array elements void Foo() { string s; Console.WriteLine(s);  // Error }
Statements Labeled Statements &  goto goto  can be used to transfer control within or out of a block, but not into a nested block static void Find(int value, int[,] values,  out int row, out int col) { int i, j; for (i = 0; i < values.GetLength(0); i++) for (j = 0; j < values.GetLength(1); j++) if (values[i, j] == value) goto found; throw new InvalidOperationException(“Not found&quot;); found: row = i; col = j; }
Statements Expression Statements Statements must do work Assignment, method call,  ++ ,  -- ,  new static void Main() { int a, b = 2, c = 3; a = b + c; a++; MyClass.Foo(a,b,c); Console.WriteLine(a + b + c); a == 2;    // ERROR! }
Statements if  Statement Requires  bool  expression int Test(int a, int b) { if (a > b) return 1; else if (a < b) return -1; else return 0; }
Statements switch  Statement Can branch on any predefined type  (including  string ) or  enum User-defined types can provide implicit conversion  to these types Must explicitly state how to end case With  break ,  goto case ,  goto label ,  return ,  throw  or  continue Eliminates fall-through bugs Not needed if no code supplied after the label
Statements switch  Statement int Test(string label) { int result; switch(label) { case null: goto case “runner-up”; case “fastest”: case “winner”: result = 1; break; case “runner-up”: result = 2; break; default: result = 0; } return result; }
Statements while  Statement Requires bool expression int i = 0; while (i < 5) { ... i++; } int i = 0; do { ... i++; } while (i < 5); while (true) { ... }
Statements for  Statement for (int i=0; i < 5; i++) { ... } for (;;) { ... }
Statements  foreach  Statement Iteration of arrays public static void Main(string[] args) { foreach (string s in args)  Console.WriteLine(s); }
Statements  foreach  Statement Iteration of user-defined collections Created by implementing  IEnumerable foreach (Customer c in customers.OrderBy(&quot;name&quot;)) { if (c.Orders.Count != 0) { ... } }
Statements Jump Statements break Exit inner-most loop continue End iteration of inner-most loop goto <label> Transfer execution to label statement return [<expression>] Exit a method throw See exception handling
Statements Exception Handling Exceptions are the C# mechanism for handling unexpected error conditions Superior to returning status values Can’t be ignored Don’t have to handled at the point they occur Can be used even where values are not returned (e.g. accessing a property) Standard exceptions are provided
Statements Exception Handling try...catch...finally  statement try  block contains code that could throw an exception catch  block handles exceptions Can have multiple catch blocks to handle different kinds of exceptions finally  block contains code that will always be executed Cannot use jump statements (e.g.  goto )  to exit a finally block
Statements Exception Handling throw  statement raises an exception An exception is represented as an instance of  System.Exception  or derived class Contains information about the exception Properties Message StackTrace InnerException You can rethrow an exception, or catch  one exception and throw another
Statements Exception Handling try { Console.WriteLine(&quot;try&quot;); throw new Exception(“message”); } catch (ArgumentNullException e) { Console.WriteLine(“caught null argument&quot;); } catch { Console.WriteLine(&quot;catch&quot;); } finally { Console.WriteLine(&quot;finally&quot;); }
Statements Synchronization Multi-threaded applications have to protect against concurrent access to data Must prevent data corruption The  lock  statement uses an instance to provide mutual exclusion Only one  lock  statement can have access to the same instance Actually uses the .NET Framework  System.Threading.Monitor  class to  provide mutual exclusion
Statements Synchronization public class CheckingAccount { decimal balance; public void Deposit(decimal amount) { lock (this) { balance += amount; } } public void Withdraw(decimal amount) { lock (this) { balance -= amount; } } }
Statements using  Statement C# uses automatic memory management (garbage collection) Eliminates most memory management problems However, it results in non-deterministic finalization No guarantee as to when and if object destructors  are called
Statements using  Statement Objects that need to be cleaned up after use should implement the  System.IDisposable  interface One method:  Dispose() The  using  statement allows you to create an instance, use it, and then ensure that  Dispose  is called when done  Dispose  is guaranteed to be called, as if it were in a  finally  block
Statements using  Statement public class MyResource : IDisposable { public void MyResource() { // Acquire valuble resource } public void Dispose() { // Release valuble resource } public void DoSomething() { ... } } using (MyResource r = new MyResource()) { r.DoSomething(); } // r.Dispose() is called
Statements checked  and  unchecked  Statements The  checked  and  unchecked  statements allow you to control overflow checking for integral-type arithmetic operations and conversions checked  forces checking unchecked  forces no checking Can use both as block statements or as an expression Default is  unchecked Use the  /checked  compiler option to make  checked  the default
Statements Basic Input/Output Statements Console applications System.Console.WriteLine(); System.Console.ReadLine(); Windows applications System.WinForms.MessageBox.Show(); string v1 = “some value”; MyObject v2 = new MyObject(); Console.WriteLine(“First is {0}, second is {1}”, v1, v2);
Agenda Hello World Design Goals of C# Types Program Structure Statements Operators Using Visual Studio.NET Using the .NET Framework SDK
Operators Overview C# provides a fixed set of operators, whose meaning is defined for the predefined types Some operators can be overloaded (e.g.  + ) The following table summarizes the C# operators by category Categories are in order of decreasing precedence Operators in each category have the same precedence
Operators Precedence Grouping: (x) Member access: x.y Method call: f(x) Indexing: a[x] Post-increment: x++ Post-decrement: x— Constructor call: new Type retrieval: typeof Arithmetic check on: checked Arithmetic check off: unchecked Primary Operators Category
Operators Precedence Positive value of: + Negative value of: - Not: ! Bitwise complement: ~ Pre-increment: ++x Post-decrement: --x Type cast: (T)x Unary Multiply: * Divide: / Division remainder: % Multiplicative Operators Category
Operators Precedence Shift bits left: << Shift bits right: >> Shift Less than: < Greater than: > Less than or equal to: <= Greater than or equal to: >= Type equality/compatibility: is Type conversion: as Relational Add: + Subtract: - Additive Operators Category
Operators Precedence Equals: == Not equals: != Equality || Logical OR ^ Bitwise XOR | Bitwise OR && Logical AND & Bitwise AND Operators Category
Operators Precedence ?: Ternary conditional =, *=, /=, %=, +=, -=, <<=, >>=,  &=, ^=, |= Assignment Operators Category
Operators Associativity Assignment and ternary conditional operators are right-associative Operations performed right to left x = y = z   evaluates as  x = (y = z) All other binary operators are left-associative Operations performed left to right x + y + z   evaluates as  (x + y) + z Use parentheses to control order
Agenda Hello World Design Goals of C# Types Program Structure Statements Operators Using Visual Studio.NET Using the .NET Framework SDK
Using Visual Studio.NET Types of projects Console Application Windows Application Web Application Web Service Windows Service Class Library ...
Using Visual Studio.NET Windows Solution Explorer Class View Properties Output Task List Object Browser Server Explorer Toolbox
Using Visual Studio.NET Building Debugging Break points References Saving
Agenda Hello World Design Goals of C# Types Program Structure Statements Operators Using Visual Studio.NET Using the .NET Framework SDK
Using .NET Framework SDK Compiling from command line csc /r:System.WinForms.dll class1.cs file1.cs
More Resources http://msdn.microsoft.com http://windows.oreilly.com/news/hejlsberg_0800.html http://www.csharphelp.com/ http://www.csharp-station.com/ http://www.csharpindex.com/ http://msdn.microsoft.com/msdnmag/issues/0900/csharp/csharp.asp http://www.hitmill.com/programming/dotNET/csharp.html http://www.c-sharpcorner.com/ http://msdn.microsoft.com/library/default.asp?URL=/library/dotnet/csspec/vclrfcsharpspec_Start.htm

Introduction To C#

  • 1.
  • 2.
    Prerequisites This moduleassumes that you understand the fundamentals of Programming Variables, statements, functions, loops, etc. Object-oriented programming Classes, inheritance, polymorphism, members, etc. C++ or Java
  • 3.
    Learning Objectives C#design goals Fundamentals of the C# language Types, program structure, statements, operators Be able to begin writing and debugging C# programs Using the .NET Framework SDK Using Visual Studio.NET Be able to write individual C# methods
  • 4.
    Agenda Hello WorldDesign Goals of C# Types Program Structure Statements Operators Using Visual Studio.NET Using the .NET Framework SDK
  • 5.
    Hello World usingSystem; class Hello { static void Main( ) { Console.WriteLine(&quot;Hello world&quot;); Console.ReadLine(); // Hit enter to finish } }
  • 6.
    Agenda Hello WorldDesign Goals of C# Types Program Structure Statements Operators Using Visual Studio.NET Using the .NET Framework SDK
  • 7.
    Design Goals ofC# The Big Ideas Component-orientation Everything is an object Robust and durable software Preserving your investment
  • 8.
    Design Goals ofC# Component-Orientation C# is the first “Component-Oriented” language in the C/C++ family What is a component? An independent module of reuse and deployment Coarser-grained than objects (objects are language-level constructs) Includes multiple classes Often language-independent In general, component writer and user don’t know each other, don’t work for the same company, and don’t use the same language
  • 9.
    Design Goals ofC# Component-Orientation Component concepts are first class Properties, methods, events Design-time and run-time attributes Integrated documentation using XML Enables “one-stop programming” No header files, IDL, etc. Can be embedded in ASP pages
  • 10.
    Design Goals ofC# Everything is an Object Traditional views C++, Java™: Primitive types are “magic” and do not interoperate with objects Smalltalk, Lisp: Primitive types are objects, but at some performance cost C# unifies with no performance cost Deep simplicity throughout system Improved extensibility and reusability New primitive types: Decimal, SQL… Collections, etc., work for all types
  • 11.
    Design Goals ofC# Robust and Durable Software Garbage collection No memory leaks and stray pointers Exceptions Type-safety No uninitialized variables, no unsafe casts Versioning Avoid common errors E.g. if (x = y) ... One-stop programming Fewer moving parts
  • 12.
    Design Goals ofC# Preserving Your Investment C++ Heritage Namespaces, pointers (in unsafe code), unsigned types, etc. Some changes, but no unnecessary sacrifices Interoperability What software is increasingly about C# talks to XML, SOAP, COM, DLLs, and any .NET Framework language Increased productivity Short learning curve Millions of lines of C# code in .NET
  • 13.
    Agenda Hello WorldDesign Goals of C# Types Program Structure Statements Operators Using Visual Studio.NET Using the .NET Framework SDK
  • 14.
    Types Overview AC# program is a collection of types Classes, structs, enums, interfaces, delegates C# provides a set of predefined types E.g. int , byte , char , string , object , … You can create your own types All data and code is defined within a type No global variables, no global functions
  • 15.
    Types Overview Typescontain: Data members Fields, constants, arrays Events Function members Methods, operators, constructors, destructors Properties, indexers Other types Classes, structs, enums, interfaces, delegates
  • 16.
    Types Overview Typescan be instantiated… …and then used: call methods, get and set properties, etc. Can convert from one type to another Implicitly and explicitly Types are organized Namespaces, files, assemblies There are two categories of types: value and reference Types are arranged in a hierarchy
  • 17.
    Types UnifiedType System Value types Directly contain data Cannot be null Reference types Contain references to objects May be null int i = 123; string s = &quot;Hello world&quot;; 123 i s &quot;Hello world&quot;
  • 18.
    Types UnifiedType System Value types Primitives int i; float x; Enums enum State { Off, On } Structs struct Point {int x,y;} Reference types Root object String string Classes class Foo: Bar, IFoo {...} Interfaces interface IFoo: IBar {...} Arrays string[] a = new string[10]; Delegates delegate void Empty();
  • 19.
    Types UnifiedType System Yes No Aliasing (in a scope) May be null Always has value Nullability Copy reference Copy data Assignment means null 0 Default value Heap Stack, member Allocated on Memory location Actual value Variable holds Reference (Class) Value (Struct)
  • 20.
    Types UnifiedType System Benefits of value types No heap allocation, less GC pressure More efficient use of memory Less reference indirection Unified type system No primitive/object dichotomy
  • 21.
    Types Conversions Implicitconversions Occur automatically Guaranteed to succeed No information (precision) loss Explicit conversions Require a cast May not succeed Information (precision) might be lost Both implicit and explicit conversions can be user-defined
  • 22.
    Types Conversions intx = 123456; long y = x; // implicit short z = (short)x; // explicit double d = 1.2345678901234; float f = (float)d; // explicit long l = (long)d; // explicit
  • 23.
    Types Unified TypeSystem Everything is an object All types ultimately inherit from object Any piece of data can be stored, transported, and manipulated with no extra work
  • 24.
    Types Unified TypeSystem Polymorphism The ability to perform an operation on an object without knowing the precise type of the object void Poly(object o) { Console.WriteLine(o.ToString()); } Poly(42); Poly(“abcd”); Poly(12.345678901234m); Poly(new Point(23,45));
  • 25.
    Types Unified TypeSystem Question: How can we treat value and reference types polymorphically? How does an int (value type) get converted into an object (reference type)? Answer: Boxing! Only value types get boxed Reference types do not get boxed
  • 26.
    Types Unified TypeSystem Boxing Copies a value type into a reference type ( object ) Each value type has corresponding “hidden” reference type Note that a reference-type copy is made of the value type Value types are never aliased Value type is converted implicitly to object , a reference type Essentially an “up cast”
  • 27.
    Types Unified TypeSystem Unboxing Inverse operation of boxing Copies the value out of the box Copies from reference type to value type Requires an explicit conversion May not succeed (like all explicit conversions) Essentially a “down cast”
  • 28.
    Types Unified TypeSystem Boxing and unboxing int i = 123; object o = i; int j = (int)o; 123 i o 123 j 123 System.Int32
  • 29.
    Types Unified TypeSystem Benefits of boxing Enables polymorphism across all types Collection classes work with all types Eliminates need for wrapper classes Replaces OLE Automation's Variant Lots of examples in .NET Framework Hashtable t = new Hashtable(); t.Add(0, &quot;zero&quot;); t.Add(1, &quot;one&quot;); t.Add(2, &quot;two&quot;); string s = string.Format( &quot;Your total was {0} on {1}&quot;, total, date);
  • 30.
    Types Unified TypeSystem Disadvantages of boxing Performance cost The need for boxing will decrease when the CLR supports generics (similar to C++ templates)
  • 31.
    Types Predefined TypesValue Integral types Floating point types decimal bool char Reference object string
  • 32.
    Predefined Types ValueTypes All are predefined structs bool Logical char Character float, double, decimal Floating point byte, ushort, uint, ulong Unsigned sbyte, short, int, long Signed
  • 33.
    Predefined Types IntegralTypes No 2 System.UInt16 ushort No 4 System.UInt32 uint No 1 System.Byte byte Yes 8 System.Int64 long 8 4 2 1 Size (bytes) No System.UInt64 ulong Yes System.Int32 int Yes System.Int16 short Yes System.Sbyte sbyte Signed? System Type C# Type
  • 34.
    Predefined Types FloatingPoint Types Follows IEEE 754 specification Supports ± 0, ± Infinity, NaN 8 4 Size (bytes) System.Double double System.Single float System Type C# Type
  • 35.
    Predefined Types decimal128 bits Essentially a 96 bit value scaled by a power of 10 Decimal values represented precisely Doesn’t support signed zeros, infinities or NaN 16 Size (bytes) System.Decimal decimal System Type C# Type
  • 36.
    Predefined Types decimalAll integer types can be implicitly converted to a decimal type Conversions between decimal and floating types require explicit conversion due to possible loss of precision s * m * 10e s = 1 or –1 0  m  296 -28  e  0
  • 37.
    Predefined Types IntegralLiterals Integer literals can be expressed as decimal or hexadecimal U or u: uint or ulong L or l: long or ulong UL or ul: ulong 123 // Decimal 0x7B // Hexadecimal 123U // Unsigned 123ul // Unsigned long 123L // Long
  • 38.
    Predefined Types RealLiterals F or f: float D or d: double M or m: decimal 123f // Float 123D // Double 123.456m // Decimal 1.23e2f // Float 12.3E1M // Decimal
  • 39.
    Predefined Types boolRepresents logical values Literal values are true and false Cannot use 1 and 0 as boolean values No standard conversion between other types and bool 1 (2 for arrays) Size (bytes) System.Boolean bool System Type C# Type
  • 40.
    Predefined Types charRepresents a Unicode character Literals ‘A’ // Simple character ‘\u0041’ // Unicode ‘\x0041’ // Unsigned short hexadecimal ‘\n’ // Escape sequence character 2 Size (bytes) System.Char Char System Type C# Type
  • 41.
    Predefined Types charEscape sequence characters (partial list) 0x000A New line \n 0x0000 Null \0 0x005C Backslash \\ 0x0022 Double quote \” 0x000D Carriage return \r 0x0027 Single quote \’ 0x0009 Value Tab \t Meaning Char
  • 42.
    Predefined Types ReferenceTypes string Character string object Root type
  • 43.
    Predefined Types objectRoot of object hierarchy Storage (book keeping) overhead 0 bytes for value types 8 bytes for reference types An actual reference (not the object) uses 4 bytes 0/8 overhead Size (bytes) System.Object object System Type C# Type
  • 44.
    Predefined Types object Public Methods public bool Equals(object) protected void Finalize() public int GetHashCode() public System.Type GetType() protected object MemberwiseClone() public void Object() public string ToString()
  • 45.
    Predefined Types stringAn immutable sequence of Unicode characters Reference type Special syntax for literals string s = “I am a string”; 20 minimum Size (bytes) System.String String System Type C# Type
  • 46.
    Predefined Types stringNormally have to use escape characters Verbatim string literals Most escape sequences ignored Except for “” Verbatim literals can be multi-line string s1= “\\\\server\\fileshare\\filename.cs”; string s2 = @“\\server\fileshare\filename.cs”;
  • 47.
    Types User-definedTypes User-defined types enum Enumerations interface Interface delegate Function pointer struct Value type class Reference type int[], string[] Arrays
  • 48.
    Types EnumsAn enum defines a type name for a related group of symbolic constants Choices must be known at compile-time Strongly typed No implicit conversions to/from int Can be explicitly converted Operators: +, -, ++, --, &, |, ^, ~, … Can specify underlying type byte, sbyte, short, ushort, int, uint, long, ulong
  • 49.
    Types Enumsenum Color: byte { Red = 1, Green = 2, Blue = 4, Black = 0, White = Red | Green | Blue } Color c = Color.Black; Console.WriteLine(c); // 0 Console.WriteLine(c.Format()); // Black
  • 50.
    Types EnumsAll enums derive from System.Enum Provides methods to determine underlying type test if a value is supported initialize from string constant retrieve all values in enum …
  • 51.
    Types ArraysArrays allow a group of elements of a specific type to be stored in a contiguous block of memory Arrays are reference types Derived from System.Array Zero-based Can be multidimensional Arrays know their length(s) and rank Bounds checking
  • 52.
    Types ArraysDeclare Allocate Initialize Access and assign Enumerate int[] primes; int[] primes = new int[9]; int[] prime = new int[] {1,2,3,5,7,11,13,17,19}; int[] prime = {1,2,3,5,7,11,13,17,19}; prime2[i] = prime[i]; foreach (int i in prime) Console.WriteLine(i);
  • 53.
    Types ArraysMultidimensional arrays Rectangular int[,] matR = new int[2,3]; Can initialize declaratively int[,] matR = new int[2,3] { {1,2,3}, {4,5,6} }; Jagged An array of arrays int[][] matJ = new int[2][]; Must initialize procedurally
  • 54.
    Types InterfacesAn interface defines a contract Includes methods, properties, indexers, events Any class or struct implementing an interface must support all parts of the contract Interfaces provide polymorphism Many classes and structs may implement a particular interface Contain no implementation Must be implemented by a class or struct
  • 55.
    Types ClassesUser-defined reference type Similar to C++, Java classes Single class inheritance Multiple interface inheritance
  • 56.
    Types ClassesMembers Constants, fields, methods, operators, constructors, destructors Properties, indexers, events Static and instance members Member access public , protected , private , internal , protected internal Default is private Instantiated with new operator
  • 57.
    Types StructsSimilar to classes, but User-defined value type Always inherits from object Ideal for lightweight objects int , float , double , etc., are all structs User-defined “primitive” types Complex, point, rectangle, color, rational Multiple interface inheritance Same members as class Member access public , internal , private Instantiated with new operator
  • 58.
    Types Classesand Structs struct SPoint { int x, y; ... } class CPoint { int x, y; ... } SPoint sp = new SPoint(10, 20); CPoint cp = new CPoint(10, 20); 10 20 sp cp 10 20 CPoint
  • 59.
    Types DelegatesA delegate is a reference type that defines a method signature When instantiated, a delegate holds one or more methods Essentially an object-oriented function pointer Foundation for framework events
  • 60.
    Agenda Hello WorldDesign Goals of C# Types Program Structure Statements Operators Using Visual Studio.NET Using the .NET Framework SDK
  • 61.
    Program Structure OverviewOrganizing Types Namespaces References Main Method Syntax
  • 62.
    Program Structure OrganizingTypes Physical organization Types are defined in files Files are compiled into modules Modules are grouped into assemblies Assembly Module File Type
  • 63.
    Program Structure OrganizingTypes Types are defined in files A file can contain multiple types Each type is defined in a single file Files are compiled into modules Module is a DLL or EXE A module can contain multiple files Modules are grouped into assemblies Assembly can contain multiple modules Assemblies and modules are often 1:1
  • 64.
    Program Structure OrganizingTypes Types are defined in ONE place “One-stop programming” No header and source files to synchronize Code is written “in-line” Declaration and definition are one and the same A type must be fully defined in one file Can’t put individual methods in different files No declaration order dependence No forward references required
  • 65.
    Program Structure NamespacesNamespaces provide a way to uniquely identify a type Provides logical organization of types Namespaces can span assemblies Can nest namespaces There is no relationship between namespaces and file structure (unlike Java) The fully qualified name of a type includes all namespaces
  • 66.
    Program Structure Namespacesnamespace N1 {     // N1 class C1 {   // N1.C1 class C2 {   // N1.C1.C2 }     }     namespace N2 {    // N1.N2 class C2 { // N1.N2.C2     }     } }
  • 67.
    Program Structure NamespacesThe using statement lets you use types without typing the fully qualified name Can always use a fully qualified name using N1; C1 a; // The N1. is implicit N1.C1 b; // Fully qualified name C2 c; // Error! C2 is undefined N1.N2.C2 d; // One of the C2 classes C1.C2 e; // The other one
  • 68.
    Program Structure NamespacesThe using statement also lets you create aliases using C1 = N1.N2.C1; using N2 = N1.N2; C1 a; // Refers to N1.N2.C1 N2.C1 b; // Refers to N1.N2.C1
  • 69.
    Program Structure NamespacesBest practice: Put all of your types in a unique namespace Have a namespace for your company, project, product, etc. Look at how the .NET Framework classes are organized
  • 70.
    Program Structure ReferencesIn Visual Studio you specify references for a project Each reference identifies a specific assembly Passed as reference ( /r or /reference ) to the C# compiler csc HelloWorld.cs /reference:System.WinForms.dll
  • 71.
    Program Structure Namespacesvs. References Namespaces provide language-level naming shortcuts Don’t have to type a long fully qualified name over and over References specify which assembly to use
  • 72.
    Program Structure MainMethod Execution begins at the static Main() method Can have only one method with one of the following signatures in an assembly static void Main() static int Main() static void Main(string[] args) static int Main(string[] args)
  • 73.
    Program Structure SyntaxIdentifiers Names for types, methods, fields, etc. Must be whole word – no white space Unicode characters Begins with letter or underscore Case sensitive Must not clash with keyword Unless prefixed with @
  • 74.
    Agenda Hello WorldDesign Goals of C# Types Program Structure Statements Operators Using Visual Studio.NET Using the .NET Framework SDK
  • 75.
    Statements Overview HighC++ fidelity if , while , do require bool condition goto can’t jump into blocks switch statement No fall-through foreach statement checked and unchecked statements Expression statements must do work void Foo() { i == 1; // error }
  • 76.
    Statements Overview Statementlists Block statements Labeled statements Declarations Constants Variables Expression statements checked, unchecked lock using Conditionals if switch Loop Statements while do for foreach Jump Statements break continue goto return throw Exception handling try throw
  • 77.
    Statements Syntax Statementsare terminated with a semicolon ( ; ) Just like C, C++ and Java Block statements { ... } don’t need a semicolon
  • 78.
    Statements Syntax Comments// Comment a single line, C++ style /* Comment multiple lines, C style */
  • 79.
    Statements Statement Lists& Block Statements Statement list: one or more statements in sequence Block statement: a statement list delimited by braces { ... } static void Main() { F(); G(); { // Start block H(); ; // Empty statement I(); } // End block }
  • 80.
    Statements Variables andConstants static void Main() { const float pi = 3.14f; const int r = 123; Console.WriteLine(pi * r * r); int a; int b = 2, c = 3; a = 1; Console.WriteLine(a + b + c); }
  • 81.
    Statements Variables andConstants The scope of a variable or constant runs from the point of declaration to the end of the enclosing block
  • 82.
    Statements Variables andConstants Within the scope of a variable or constant it is an error to declare another variable or constant with the same name { int x; { int x; // Error: can’t hide variable x } }
  • 83.
    Statements Variables Variablesmust be assigned a value before they can be used Explicitly or automatically Called definite assignment Automatic assignment occurs for static fields, class instance fields and array elements void Foo() { string s; Console.WriteLine(s); // Error }
  • 84.
    Statements Labeled Statements& goto goto can be used to transfer control within or out of a block, but not into a nested block static void Find(int value, int[,] values, out int row, out int col) { int i, j; for (i = 0; i < values.GetLength(0); i++) for (j = 0; j < values.GetLength(1); j++) if (values[i, j] == value) goto found; throw new InvalidOperationException(“Not found&quot;); found: row = i; col = j; }
  • 85.
    Statements Expression StatementsStatements must do work Assignment, method call, ++ , -- , new static void Main() { int a, b = 2, c = 3; a = b + c; a++; MyClass.Foo(a,b,c); Console.WriteLine(a + b + c); a == 2; // ERROR! }
  • 86.
    Statements if Statement Requires bool expression int Test(int a, int b) { if (a > b) return 1; else if (a < b) return -1; else return 0; }
  • 87.
    Statements switch Statement Can branch on any predefined type (including string ) or enum User-defined types can provide implicit conversion to these types Must explicitly state how to end case With break , goto case , goto label , return , throw or continue Eliminates fall-through bugs Not needed if no code supplied after the label
  • 88.
    Statements switch Statement int Test(string label) { int result; switch(label) { case null: goto case “runner-up”; case “fastest”: case “winner”: result = 1; break; case “runner-up”: result = 2; break; default: result = 0; } return result; }
  • 89.
    Statements while Statement Requires bool expression int i = 0; while (i < 5) { ... i++; } int i = 0; do { ... i++; } while (i < 5); while (true) { ... }
  • 90.
    Statements for Statement for (int i=0; i < 5; i++) { ... } for (;;) { ... }
  • 91.
    Statements foreach Statement Iteration of arrays public static void Main(string[] args) { foreach (string s in args) Console.WriteLine(s); }
  • 92.
    Statements foreach Statement Iteration of user-defined collections Created by implementing IEnumerable foreach (Customer c in customers.OrderBy(&quot;name&quot;)) { if (c.Orders.Count != 0) { ... } }
  • 93.
    Statements Jump Statementsbreak Exit inner-most loop continue End iteration of inner-most loop goto <label> Transfer execution to label statement return [<expression>] Exit a method throw See exception handling
  • 94.
    Statements Exception HandlingExceptions are the C# mechanism for handling unexpected error conditions Superior to returning status values Can’t be ignored Don’t have to handled at the point they occur Can be used even where values are not returned (e.g. accessing a property) Standard exceptions are provided
  • 95.
    Statements Exception Handlingtry...catch...finally statement try block contains code that could throw an exception catch block handles exceptions Can have multiple catch blocks to handle different kinds of exceptions finally block contains code that will always be executed Cannot use jump statements (e.g. goto ) to exit a finally block
  • 96.
    Statements Exception Handlingthrow statement raises an exception An exception is represented as an instance of System.Exception or derived class Contains information about the exception Properties Message StackTrace InnerException You can rethrow an exception, or catch one exception and throw another
  • 97.
    Statements Exception Handlingtry { Console.WriteLine(&quot;try&quot;); throw new Exception(“message”); } catch (ArgumentNullException e) { Console.WriteLine(“caught null argument&quot;); } catch { Console.WriteLine(&quot;catch&quot;); } finally { Console.WriteLine(&quot;finally&quot;); }
  • 98.
    Statements Synchronization Multi-threadedapplications have to protect against concurrent access to data Must prevent data corruption The lock statement uses an instance to provide mutual exclusion Only one lock statement can have access to the same instance Actually uses the .NET Framework System.Threading.Monitor class to provide mutual exclusion
  • 99.
    Statements Synchronization publicclass CheckingAccount { decimal balance; public void Deposit(decimal amount) { lock (this) { balance += amount; } } public void Withdraw(decimal amount) { lock (this) { balance -= amount; } } }
  • 100.
    Statements using Statement C# uses automatic memory management (garbage collection) Eliminates most memory management problems However, it results in non-deterministic finalization No guarantee as to when and if object destructors are called
  • 101.
    Statements using Statement Objects that need to be cleaned up after use should implement the System.IDisposable interface One method: Dispose() The using statement allows you to create an instance, use it, and then ensure that Dispose is called when done Dispose is guaranteed to be called, as if it were in a finally block
  • 102.
    Statements using Statement public class MyResource : IDisposable { public void MyResource() { // Acquire valuble resource } public void Dispose() { // Release valuble resource } public void DoSomething() { ... } } using (MyResource r = new MyResource()) { r.DoSomething(); } // r.Dispose() is called
  • 103.
    Statements checked and unchecked Statements The checked and unchecked statements allow you to control overflow checking for integral-type arithmetic operations and conversions checked forces checking unchecked forces no checking Can use both as block statements or as an expression Default is unchecked Use the /checked compiler option to make checked the default
  • 104.
    Statements Basic Input/OutputStatements Console applications System.Console.WriteLine(); System.Console.ReadLine(); Windows applications System.WinForms.MessageBox.Show(); string v1 = “some value”; MyObject v2 = new MyObject(); Console.WriteLine(“First is {0}, second is {1}”, v1, v2);
  • 105.
    Agenda Hello WorldDesign Goals of C# Types Program Structure Statements Operators Using Visual Studio.NET Using the .NET Framework SDK
  • 106.
    Operators Overview C#provides a fixed set of operators, whose meaning is defined for the predefined types Some operators can be overloaded (e.g. + ) The following table summarizes the C# operators by category Categories are in order of decreasing precedence Operators in each category have the same precedence
  • 107.
    Operators Precedence Grouping:(x) Member access: x.y Method call: f(x) Indexing: a[x] Post-increment: x++ Post-decrement: x— Constructor call: new Type retrieval: typeof Arithmetic check on: checked Arithmetic check off: unchecked Primary Operators Category
  • 108.
    Operators Precedence Positivevalue of: + Negative value of: - Not: ! Bitwise complement: ~ Pre-increment: ++x Post-decrement: --x Type cast: (T)x Unary Multiply: * Divide: / Division remainder: % Multiplicative Operators Category
  • 109.
    Operators Precedence Shiftbits left: << Shift bits right: >> Shift Less than: < Greater than: > Less than or equal to: <= Greater than or equal to: >= Type equality/compatibility: is Type conversion: as Relational Add: + Subtract: - Additive Operators Category
  • 110.
    Operators Precedence Equals:== Not equals: != Equality || Logical OR ^ Bitwise XOR | Bitwise OR && Logical AND & Bitwise AND Operators Category
  • 111.
    Operators Precedence ?:Ternary conditional =, *=, /=, %=, +=, -=, <<=, >>=, &=, ^=, |= Assignment Operators Category
  • 112.
    Operators Associativity Assignmentand ternary conditional operators are right-associative Operations performed right to left x = y = z evaluates as x = (y = z) All other binary operators are left-associative Operations performed left to right x + y + z evaluates as (x + y) + z Use parentheses to control order
  • 113.
    Agenda Hello WorldDesign Goals of C# Types Program Structure Statements Operators Using Visual Studio.NET Using the .NET Framework SDK
  • 114.
    Using Visual Studio.NETTypes of projects Console Application Windows Application Web Application Web Service Windows Service Class Library ...
  • 115.
    Using Visual Studio.NETWindows Solution Explorer Class View Properties Output Task List Object Browser Server Explorer Toolbox
  • 116.
    Using Visual Studio.NETBuilding Debugging Break points References Saving
  • 117.
    Agenda Hello WorldDesign Goals of C# Types Program Structure Statements Operators Using Visual Studio.NET Using the .NET Framework SDK
  • 118.
    Using .NET FrameworkSDK Compiling from command line csc /r:System.WinForms.dll class1.cs file1.cs
  • 119.
    More Resources http://msdn.microsoft.comhttp://windows.oreilly.com/news/hejlsberg_0800.html http://www.csharphelp.com/ http://www.csharp-station.com/ http://www.csharpindex.com/ http://msdn.microsoft.com/msdnmag/issues/0900/csharp/csharp.asp http://www.hitmill.com/programming/dotNET/csharp.html http://www.c-sharpcorner.com/ http://msdn.microsoft.com/library/default.asp?URL=/library/dotnet/csspec/vclrfcsharpspec_Start.htm

Editor's Notes

  • #3 The intent of this module is to teach the C# language, and how it differs from C++ and Java. It is not the intent of this module to teach how to program.
  • #4 This module is designed to update C++ and Java programmers with the fundamentals of C#.
  • #6 The Hello World application is very simple in C#. Some key points: In C# there are no global methods. Everything belongs to a class. A method named Main is the entry point for a C# application. Note that Main is spelled with a capital “M”, which is different than C and C++. The reason is that for consistency, all method names start with a capital letter in the .NET Framework The line using System; means that we’ll be accessing members of the System namespace. In a very rough comparison, a namespace could be translated to a Unit in Turbo Pascal/Delphi or a .LIB file in C/C++. So in the Hello World example, the class Console, which contains the method WriteLine belongs to the System namespace. We could avoid the “using” statement by writing the complete path of the method: System.Console.WriteLine(“Hello World”);
  • #8 First of all, C# was designed from the ground up to support components concepts like events, methods and properties. Second, everything is an object, which allows us to create some really clean designs. Third, it was designed to make it easy to create robust and maintainable software And finally, it should be able to integrate easily with everything that already exists, preserving your investment.
  • #9 C# is component-oriented, but first, what is a component? The definition of a component is still contentious. However, there is agreement that components address issues of reuse and deployment, as opposed to objects, which are language-specific concepts.
  • #10 C# is a Component Oriented Language First of all, C# was designed from the ground up to support components. It is the first language in the C/C++ family to support the concepts of components. But what defines a component? Basically it is the not only classes and methods, but also properties and events. It is not that is not possible to do component based development in C++, but you must rely usually on coding conventions like to define a property, let’s name this method as GetSomething and SetSomething. If you want to support events then it means that you need to implement this and that interface. In C#, the concept of properties, methods and events are all native. In fact, C++ only supports the concept of methods. Just as an analogy, it is not impossible to write object oriented programs in C, it is only harder than in C++. The same applies to component based development in C++ vs. C#. Also when you move to component based development you have to think in a number of other factors like separate files to describe my components, like header files in C++, IDL to describe component interfaces and so on. In C# none of these are needed since it has built-in support for these concepts, enabling what we call one stop programming, so everything can be described in the source code, instead of requiring separate files.
  • #11 Everything is an Object There are two different schools here: the purists like Smalltalk where everything is an object and C++ or Java, where primitive types are treated differently for performance reasons. Typically, when everything is an object, it means that every time that you do a simple operation like adding to numbers, it will incur on a heap allocation, which is quite expensive from the CPU standpoint compared to a stack allocated piece of memory. On the other hand, when languages threat primitive types as magic types, it means that if you implement a generic class, like a collection or array, it is not truly generic, because you either have to implement one version for each primitive type or you have to write wrapper classes to each of the primitive types so they can behave as an object. In C#, it is possible if you declare a primitive type, it is created on the stack, with all performance benefits that this brings. However it is possible to assign an integer to an object, and the runtime will automatically allocate the memory on the heap to accommodate the integer and threat it as an object. This happens automatically without requiring the programmer to write an wrapper class. Just as a side note for VB programmers: you can compare a stack allocation to a stack of paper where you can only write to the top page. As soon as you enter a function or sub you get a new page and you’re done (exit the function) you just throw away the top page. Let’s say that garbage management is really simple in this scenario. Heap allocation is like having multiple pages at your disposal and also they don’t necessary vanish when your function ends. You can imagine that it is a lot more complex, because a piece of data on page 2 could be disposed, but another piece on the same page could still be needed by a different part of the code. In other words, a lot more management is necessary.
  • #12 Prevent common mistakes from other languages C# has a lot of features to make it easier to create robust software. Every C++ programmer knows how easy is to have a pointer to an object that was already de-allocated. C# provides automatically garbage collection through the Common Language Runtime. Also, if you think about how error were handle in most of the code today, they’re mostly based on checking return codes. Exceptions provides a way to write a less code while at the same time providing a much more robust error handling mechanism. Not only exception handling is implemented in the language but it is also a inherent part of the .NET Framework Another point is that all variables are automatically initialised and it is impossible to do unsafe casts. Finally, C# is one of the first languages that provides a versioning semantics to easily support old and new clients.
  • #13 Leverage C++ knowledge, interoperability and rich class library First of all, since C# was based on C++, C++ programmers will adapt really quick. Second, interoperability is a key theme in the .NET Framework. So it is really easy to integrate C# code with existing applications Finally, the .NET Framework provides a very, very rich set of services that will make developers really productive.
  • #15 In most other purely object-oriented languages one would say that a program is a collection of classes. Not all types have all capabilities; e.g. enums are fairly constrained.
  • #18 In C# you have value types that directly hold the data on the stack and reference types that keeps a reference on the stack, but allocates the real memory on the heap. Also have pointer types in unsafe code. Will discuss those in Part 2.
  • #19 Structs and classes can be user-defined.
  • #24 Everything inherits from object, including primitive types, structs or classes.
  • #25 The example shows a function, Poly(), that is called with different types of arguments.
  • #27 Boxing and Unboxing is one of the key innovations of C# language. Instead of requiring the programmer to write wrapper code to convert from stack based memory to heap memory, you just need to assign a value type to an object and C# takes care of allocating the memory in the heap and generating a copy of that on the heap. When you assign the object to a stack based int, the value is converted to the stack again. This process is what we call Boxing and Unboxing. If an int is boxed, it still knows it’s an int.
  • #30 Main benefits of the Unified Type System: No need of wrapper code to use base types in collections or arrays No Variants anymore
  • #40 Eliminating implicit conversions between numbers and bool can help find subtle bugs.
  • #49 Enums in C# are strongly typed, which means that you can’t assign a int enum to a long, or vice versa, avoiding some typical conversion mistakes.
  • #55 In scenarios where completely different objects need to support some kind of shared functionality like, let’s say, persist to XML, classes can implement interfaces that make then compatible with even if they don’t share the same base class. This provides most of the benefits of multiple class inheritance without the nasty side-effects that this usually brings.
  • #56 Classes in C# allow single inheritance and multiple interface inheritance. Each class can contain methods, properties, events, indexers, constants, constructors, destructors, operators and members can be static (can be accessed without an object instance) or instance member (require you to have a reference to an object first)
  • #57 protected internal = protected OR internal
  • #58 To provide a really high performance object type, C# provides structs, which are stack allocated. They’re ideal for small objects and are really fast since they don’t depend on dynamic memory allocation and the garbage collector. It is also important to notice that it is not possible to inherit from an struct. No protected access because there is no inheritance.
  • #59 Again, comparing classes and structs, it is the memory layout of a struct is just a direct representation of its members directly on the stack. On a class, a reference is stored on the stack, while the object itself is stored in the heap.
  • #67 The comments show the fully qualified names. A namespace called N3.N4 is like two nested namespaces.
  • #68 Note that it is N1.C1, not N1::C1 The using statement is scoped by the namespace and/or compilation module containing it.
  • #76 In the Statements and Expressions area C# is just like C++ with some key differences to improve code robustness. Other than solving the old assignment problem in if statements, goto usage is limited to safer scenarios and switch statements require break between each options avoiding the infamous fall through bug. Also C# has a foreach statement to iterate through arrays and collections
  • #85 Also used in switch statements
  • #86 Expression statements must do work.
  • #87 Like C, C++ and Java, beware of dangling elses!
  • #91 Just like C++ and Java.
  • #92 No need to have loops with explicit bounds checking. Just use foreach.
  • #94 There is no break &lt;label&gt; or continue &lt;label&gt;.
  • #97 You can define your own exceptions by deriving it from System.Exception.
  • #98 This will print: try catch finally
  • #99 Unlike Java, you cannot specify that an entire method be locked. Experience has shown that usually an entire method does not have to be locked. Since you want to hold locks as short a period of time as possible, C# doesn’t allow you to specify it for a method.
  • #100 Two threads can call methods on CheckingAccount concurrently, but only one will be able to update balance at a time. This will prevent balance from becoming corrupted.
  • #102 The using statement is not in Beta 1
  • #107 The + operator is overloaded to mean addition for numbers and concatenation for strings.