>, ?: … C like control: if () … else … for (…; …; …) … break … while (…) … continue … do … while (…) switch (…) … case … default no fall through, also switch on strings"> >, ?: … C like control: if () … else … for (…; …; …) … break … while (…) … continue … do … while (…) switch (…) … case … default no fall through, also switch on strings">
Download presentation
Presentation is loading. Please wait.
Published byWilliam Cooper Modified over 6 years ago
1
C# part I C:\> csc hello.cs … … C:\> hello.exe Hello, World!
using System; public class MyClass } public static void Main() { Console.WriteLine("Hello, World!"); } } hello.cs C:\> csc hello.cs … … C:\> hello.exe Hello, World!
2
Genealogy Designer: Anders Hejlsberg (Microsoft)
Designer of Turbo Pascal, Visual J++, Delphi (Borland) C Dynasty: Play on Words C++ increment C by one. C# the musical note half tone above C Yet another curly bracket programming language Grouping: {} Terminstic camp: statements terminated by ";" C operators: ++ % != += && & ^, >>, ?: … C like control: if () … else … for (…; …; …) … break … while (…) … continue … do … while (…) switch (…) … case … default no fall through, also switch on strings
3
Design Principles All the Good Things: Programmer Protection:
Simplicity, General Purpose, Portability, Object Oriented Programmer Protection: Strong Nominative Typing Array Bounds Checking Garbage Collection Check against using uninitialized variables No "hiding" by inner scopes Evolutionary: dramatic changes in each language version Learn from Java mistakes: (no checked exceptions, since Anders Hejlsberg doesn't know yet how to do these right) Efficiency: Not at any price Better Java? Developed by Microsoft Runs on CLR "Common Language Runtime" Compiles to the CIL "Common Intermediate Language" Support for "unsafe" features, including pointers.
4
Pre-Defined Types Integral Types (signed and unsigned version) : byte, sbyte, short, ushort, int, uint, long, ulong May cause conversion problems. Most programmers like byte to be unsigned. Real Numbers: float, double, decimal (28 digits) Other: bool, char (unicode), string (immutable unicode),
5
Value/Reference Semantics
Value Types Simple types: char, int, float, … Enum types Struct types Reference Types Classes, Interfaces, Delegates Nullable Value Types public enum Color {Red, Blue, Green } public struct Point { public int x, y; } char? c_null = eof() ? null : getchar(); if (c_null == null) { … } char c = c_null ?? ' '
6
Object Oriented Purity
Global Variables? No. All variables are defined in functions/classes. Global Routines? No. All routines (functions) are defined in classes. Non OO Types? No. Even primitive types belong in the OO hierarchy. OO Control Flow? No. If, while, for, … are imperative statements Preprocessor? Yes. (a good preprocessor can be used to defeat any paradigm) Allows variables, but not parameterized macros.
7
Inheritance Hierarchy
Classes: Single Inheritance Common root: System.Object Unified type system: includes all builtin types (except for void) System.ValueType:base class of all value types Implementation by seamless auto-boxing and auto-unboxing. System.Enum: base class of all enum types System.Array: base class of all arrays … Unextendable classes: denoted by keyword sealed Static classes: denoted by keyword static No non-static members Must inherit form System.Object Interfaces: Multiple Inheritance hierarchy May be implemented by classes and structs Structs: no inheritance, but may implement interfaces.
8
Reflection 3 Levels: similar to Java and little-Smallatk
using System; using System.Reflection; public static class FindLevels { private static void traverse(Object o) { for (int n = 0; ; o = o.GetType()) { Console.WriteLine( "L"+ ++n + ": " + o + ".GetType() = " o.GetType()); if (o == o.GetType()) break; } } public static void Main() { traverse ( ); } } L1: GetType() = System.Double L2: System.Double.GetType() = System.RuntimeType L3: System.RuntimeType.GetType() = System.RuntimeType
9
Exploring Hierarchy with Reflection
using System; using System.Reflection; public static class FindSuperTypes { private static String pName(Type t) { return t.BaseType == null ? "null" : t.BaseType.ToString(); } private static void ancestory(Object o) { for (Type t = o.GetType(); t != null ; t = t.BaseType) Console.WriteLine(t + " inherits from " + pName(t)); } public static void Main() { ancestory( GetType()); } } System.RuntimeType inherits from System.Type System.Type inherits from System.Reflection.MemberInfo System.Reflection.MemberInfo inherits from System.Object System.Object inherits from null
10
Covariance Suppose B is a subtype of A: then an array of B is a subtype of an array of A. Like Java, unlike C++. Runtime type checking: in assignments to array elements. No Array Covariance of Value types. Object a[] = new int[5]; // error Method arguments and return type are no-variant. class A{}; void f(A[] a) { a[0] = new A();//OK? } class B: A {} // Legal assignment A[] x = new B[]; // Legal call f(x);
11
A Universal Dump Array Function
class EM: ICloneable { // Will dump any array thanks to array co-variance public static void print( String title, Object[] array) { if (array.Length == 0) return; Console.WriteLine(title + ":"); foreach (Object item in array) Console.WriteLine(" " + item); Console.WriteLine(); } // No co-variance of return type of methods public Object Clone() { return new EM(); } … }
12
Accessibility Five Levels Default Levels public Unlimited access
protected This class and all subclasses internal Classes define in this "assembly" protected internal This assembly and subclasses Nicknamed internal public private This class only Default Levels namespace public enum public class private interface public struct private others internal
13
Class/Struct Member Kinds
Instance Constructors: similar to C++/Java constructors Dynamic binding within constructors Finalizer: Syntax as C++ destructor; semantics as Java finalizer. Static Constructors: similar to Java static initiliazers Constants: value computed at compile time implicitly static Instance Fields: like Java/C++ Instance Readonly Fields: with readonly keyword initialized by constructor / static constructor Static Fields: with static keyword Static Readonly Fields: Initialized by static constructor only Methods & Static Methods: like Java/C++ Properties (and static properties): field access implemented by methods Indexers: array access implemented by methods Events (and Static Events): more on these later
14
Investigating Member Kinds
public class EM: ICloneable { public static void print(…) { … } public Object Clone() { … } static readonly public String NL = "\n"; public static void Main() { Type t = new EM().GetType(); Console.WriteLine(t+": "+t.Attributes + NL); print("Constructors", t.GetConstructors()); print("Methods", t.GetMethods()); print("Properties", t.GetProperties()); print("Fields", t.GetFields()); print("Events", t.GetEvents()); print("Interfaces", t.GetInterfaces()); } {
15
Reflection Information
EM: AutoLayout, AnsiClass, Class, Public, BeforeFieldInit Constructors: Void .ctor() Methods: Void print(System.String, System.Object[]) System.Object Clone() Void Main() System.Type GetType() System.String ToString() Boolean Equals(System.Object) Int32 GetHashCode() Fields: System.String NL Interfaces: System.ICloneable
16
Properties Property: a field implemented with methods
Varieties: read only, write only, read-write Contextual keywords: get, set, value (also add and del for events) Provide specific meaning in the code Not reserved words public struct Window { public int n_read = 0; private string title; public string Title { // read-write property get { // property getter method n_read++; return title; } set { // property setter method if (title != value)// implicit parameter return; title = value; redraw(); } } … { Window w = new Window("Initial Title"); Console.WriteLine(w.Title);// increment n_read w.Title = "My Title"; // redraw
17
Static Properties public struct HarryPotterBook { static private int count; static HarryPotterBook() {// static constructor count = she_wrote_it() ? 7 : 6; } static public int Count { // read-only static property get { return count; } } … {
18
Static Members A Node With a Static Allocator
A List Using the Static Allocator class Node { public Node Next; public String Key; public Object Data; public Node(Node next) : this(null, null, next) { } public Node(String key, Object data, Node next) { Key = key; Data = data; Next = next; } static public Node Allocate(uint n) { return n == 0 ? null : new Node(Allocate(n - 1)); class List { private Node first; public List(uint n) { first = Node.Allocate(n); } … {
19
Indexers Purpose: Implement array access with methods
Similar to properties (though no static indexers) Syntax: modifiers returnType this[IndexType pos] Variations: multi-parameters indexers read-only, write-only and read-write indexers overloaded indexers class List { … private Node nth(Node n, uint d) { if (n == null) throw new Exception("out of range"); return d == 0 ? n : nth(n.Next,d-1); } public Object this[uint i] { // indexer using ordinal position get { return nth(first, i).Data; } set { nth(first,i).Data = value; }
20
Using the Indexer 0^2 = 0 1^2 = 1 2^2 = 4 3^2 = 9 4^2 = 16
class List { static void Main() { const uint n = 5; List sq = new List(n); for (uint i = 0; i < n; i++) sq[i] = i * i; Console.WriteLine(i + "^2 = " + sq[i]); } } 0^2 = 0 1^2 = 1 2^2 = 4 3^2 = 9 4^2 = 16
21
Indexer Overloading public class List { …
private static Node find(Node n, String k) { if (n == null) return null; return n.Key.Equals(k) ? n : find(n.Next,k); } public Object this[String k] { // indexer using key get { Node n = find(first, k); return n != null ? n.Data : null; set { Node n = find(first, k); if (n != null) n.Data = value; else first = new Node(k, value, first);
22
Jerusalem Using String Indexer class List { static void Main() { …
List capitals = new List(0); capitals["Israel"] = "Jerusaelm"; capitals["Iraq"] = "Bagdad"; Console.WriteLine(capitals["Israel"]); } } Jerusalem
23
Inheritance and Binding
Method Binding: static, unless method is declared virtual virtual modifier cannot go with any of static, abstract, private or override modifiers. Properties can be virtual Overriding: inheritance is strict by default. Overriding methods must be declared as such with override keyword Cannot override non-virtual functions Use new modifier to indicate hiding Sealing: use sealed keyword to indicate that an overriding function cannot be overridden further No point in sealing a "plain" virtual function.
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.