C Sharp - part1

Download Report

Transcript C Sharp - part1

C#
part I
hello.cs
using System;
public class MyClass }
public static void Main() {
Console.WriteLine("Hello, World!");
}
}
C:\> csc hello.cs
… …
C:\> hello.exe
Hello, World!
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
2
Design Principles
• All the Good Things:
– 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.
3
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),
4
Value/Reference Semantics
• Value Types
– Simple types: char, int, float, …
– Enum types
public enum Color {Red, Blue, Green
}
– Struct types
public struct Point { public int x, y; }
• Reference Types
– Classes, Interfaces, Delegates
• Nullable Value Types
char? c_null = eof() ? null : getchar();
if (c_null == null) {
…
}
char c = c_null ?? ' '
5
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.
6
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.
7
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 (3.1415926); }
}
L1: 3.1415926.GetType() = System.Double
L2: System.Double.GetType() = System.RuntimeType
L3: System.RuntimeType.GetType() = System.RuntimeType
8
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(3.1415926.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
9
Covariance
• Suppose B is a subtype
class A{};
of A: then an array of B void f(A[] a) {
is a subtype of an array of
a[0] = new A();//OK?
A.
}
Like Java, unlike C++.
• Runtime type checking: in class B: A {}
assignments to array
elements.
// Legal assignment
• No Array Covariance of
A[] x = new B[];
Value types.
Object a[] = new int[5];
// error
• Method arguments and
return type are novariant.
// Legal call
f(x);
10
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();
}
…
}
11
• Five Levels
Accessibility
–
–
–
–
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
enum
class
interface
struct
others
public
public
private
public
private
internal
12
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
13
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());
}
{
14
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
15
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
16
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; }
}
…
{
17
Static Members
• A Node With a 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));
}
}
• A List Using the Static Allocator
class List {
private Node first;
public List(uint n) { first = Node.Allocate(n); }
…
{
18
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; }
}
…
}
19
Using the Indexer
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;
for (uint i = 0; i < n; i++)
Console.WriteLine(i + "^2 = " + sq[i]);
}
}
0^2 = 0
1^2
2^2
3^2
16 =
= 1
= 4
= 9
2^4
20
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);
}
}
}
21
Using String Indexer
class List {
static void Main() {
…
List capitals = new List(0);
capitals["Israel"] = "Jerusaelm";
capitals["Iraq"] = "Bagdad";
Console.WriteLine(capitals["Israel"]);
}
}
Jerusalem
22
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.
23