45
C# C# Yingcai Xiao Yingcai Xiao

C# Yingcai Xiao. Part I Moving from Java to C# .NET Framework ’ s Data Types: CTS Six categories of data types in CTS: system-defined: Primitives (int,

Embed Size (px)

Citation preview

Page 1: C# Yingcai Xiao. Part I Moving from Java to C# .NET Framework ’ s Data Types: CTS Six categories of data types in CTS: system-defined: Primitives (int,

C#C#

Yingcai XiaoYingcai Xiao

Page 2: C# Yingcai Xiao. Part I Moving from Java to C# .NET Framework ’ s Data Types: CTS Six categories of data types in CTS: system-defined: Primitives (int,

Part IPart IMoving from Java to C#Moving from Java to C#

Page 3: C# Yingcai Xiao. Part I Moving from Java to C# .NET Framework ’ s Data Types: CTS Six categories of data types in CTS: system-defined: Primitives (int,

.NET Framework’s Data Types: CTS Six categories of data types in CTS: system-defined:

Primitives (int, float, …)

user-defined:ClassesStructsInterfacesEnumerationsDelegates

Common Type System (CTS)

Page 4: C# Yingcai Xiao. Part I Moving from Java to C# .NET Framework ’ s Data Types: CTS Six categories of data types in CTS: system-defined: Primitives (int,

Named Space:

grouped code, used to resolve naming conflicts.

namespace mine{

int i=10; }

namespace his{

int i=20; }

mine.i = his.i;

Common Type System (CTS)

Page 5: C# Yingcai Xiao. Part I Moving from Java to C# .NET Framework ’ s Data Types: CTS Six categories of data types in CTS: system-defined: Primitives (int,

namespace WP1.CS.UA{ class Hello { public Hello() { System.Console.WriteLine("Hello, world."); } }}namespace WP2.CS{ class Hello { public Hello() {

System.Console.WriteLine("Hello, again!"); } }}

Named Space Example

Page 6: C# Yingcai Xiao. Part I Moving from Java to C# .NET Framework ’ s Data Types: CTS Six categories of data types in CTS: system-defined: Primitives (int,

namespace WP{ class Test { public static void Main() { WP1.CS.UA.Hello mc = new WP1.CS.UA.Hello(); WP2.CS.Hello mc2 = new WP2.CS.Hello(); } }}

Named Space Example

Page 7: C# Yingcai Xiao. Part I Moving from Java to C# .NET Framework ’ s Data Types: CTS Six categories of data types in CTS: system-defined: Primitives (int,

Classes

Class: a group of code and data to be instantiated to form objects.

Four categories of class members:Fields: member variablesMethods: member functionsProperties: fields exposed using accessor (get and set) methodsEvents: notifications a class is capable of firing

Page 8: C# Yingcai Xiao. Part I Moving from Java to C# .NET Framework ’ s Data Types: CTS Six categories of data types in CTS: system-defined: Primitives (int,

class Rectangle{ // Fields protected int width = 1; protected int height = 1;

// Methods public Rectangle () { } public Rectangle (int cx, int cy) { width = cx; height = cy; }

Example: How to define a class (user-defined data type)

Page 9: C# Yingcai Xiao. Part I Moving from Java to C# .NET Framework ’ s Data Types: CTS Six categories of data types in CTS: system-defined: Primitives (int,

// Accessor Methods public void setWidth(int w) { width = w; }public int getWidth() { return width; }

public void setHeight(int h) { height = h; }public int getHeight() { return height; }

} // End of Rectangle class

Example: How to define a class (user-defined data type)

Page 10: C# Yingcai Xiao. Part I Moving from Java to C# .NET Framework ’ s Data Types: CTS Six categories of data types in CTS: system-defined: Primitives (int,

Rectangle rect = new Rectangle(2,4);rect.setHeight(8);rect.setWidth(rect.getWidth() * 2); double darea = (double) (rect.getWidth() * rect.getHeight() );

We protected member fields: width and height. (Encapsulation)(1) Securer code. Methods not belonging to the class hierarchy can’t access protected members. If we don’t want anyone change the value of “width”, we just don’t provide the setWidth() method. (2) Easier to maintain the code. We can rename “width” to “w” without impacting the users of the “Rectangle” class. (3) Tedious to implement and use. If we define the member fields as public, the usage would be much easier.

rect.width *= 2;

Example: How to use a class (user-defined data type)

Page 11: C# Yingcai Xiao. Part I Moving from Java to C# .NET Framework ’ s Data Types: CTS Six categories of data types in CTS: system-defined: Primitives (int,

Can we make the member fields secure and easy to use at the same time?

Property

Page 12: C# Yingcai Xiao. Part I Moving from Java to C# .NET Framework ’ s Data Types: CTS Six categories of data types in CTS: system-defined: Primitives (int,

// Properties defined as grouped accessor methods // in the Rectangle class public int Width // group name { get { return width; } set // the input parameter is implicit: value { if (value > 0) width = value; else throw new ArgumentOutOfRangeException ( "Width must be 1 or higher"); } }

Example: How to define properties

Page 13: C# Yingcai Xiao. Part I Moving from Java to C# .NET Framework ’ s Data Types: CTS Six categories of data types in CTS: system-defined: Primitives (int,

public int Height // a field defined by type and public int Height // a field defined by type and accessor codeaccessor code {{ get { return height; }get { return height; } setset {{ if (value > 0)if (value > 0) height = value;height = value; elseelse throw new throw new ArgumentOutOfRangeException (ArgumentOutOfRangeException ( "Height must be 1 or higher");"Height must be 1 or higher"); }}}}

Example: How to define properties

Page 14: C# Yingcai Xiao. Part I Moving from Java to C# .NET Framework ’ s Data Types: CTS Six categories of data types in CTS: system-defined: Primitives (int,

public int Area // a property of only get method { get { return width * height; } }

Example: How to define properties

Page 15: C# Yingcai Xiao. Part I Moving from Java to C# .NET Framework ’ s Data Types: CTS Six categories of data types in CTS: system-defined: Primitives (int,

Properties are defined in the following format:

protected type field-name;public type property-name { get { /* return the field value */ } set { /* reset the field value */ } }

Defining Properties

A property definition is composed of• a protected or private field• a property to expose the field• which in turn consists of at least one accessor (get()/set()).

Page 16: C# Yingcai Xiao. Part I Moving from Java to C# .NET Framework ’ s Data Types: CTS Six categories of data types in CTS: system-defined: Primitives (int,

Properties are used the same way as public fields.

Rectangle rect = new Rectangle(2,4);rect.Width = 7;rect.Width *= 2; // Double the rectangle's widthint area = rect.Area; // Get the rectangle's new area //Typecast a property “value” from int to doubledouble darea = (double) rect.Area;

Advantage of Properties: allow users to access private/protected fields as if they were public fields.

Using Properties

Page 17: C# Yingcai Xiao. Part I Moving from Java to C# .NET Framework ’ s Data Types: CTS Six categories of data types in CTS: system-defined: Primitives (int,

(1) Properties are public methods (set and get) used like fields. Data is secured (encapsulated) and access is simplified.

(2) The set and get methods are called accessors. A property may not have the set (read-only properties) or the get (write-only properties), but can not miss both.

(3) The implicit input argument, value, for the set method has the same type as the property.

(4) The type of a property must be the same as the type of the field member it protects.

(5) A property can’t be overloaded, e.g., we can’t define a “public double Area { … }” after defining “public int Area { … }”. You have to use a different property name, e.g. doubleArea, to define the area property of type double.

Notes on Properties

Page 18: C# Yingcai Xiao. Part I Moving from Java to C# .NET Framework ’ s Data Types: CTS Six categories of data types in CTS: system-defined: Primitives (int,

Signature of a method: name, number of arguments, types of the arguments. Return type is not part of the signature.

Why we have to name properties of different Why we have to name properties of different types differently?types differently?

Overloading: two or more methods have the same name but different arguments.

Name Mangling encodes the name of an overloaded method with its signature (by the compiler). The internal names of the methods are unique (no internal overloading).

Property do not have any arguments, so the only way to differentiate properties of different type is by their names.

Page 19: C# Yingcai Xiao. Part I Moving from Java to C# .NET Framework ’ s Data Types: CTS Six categories of data types in CTS: system-defined: Primitives (int,

InterfacesInterfaces Interfaces

• An interface is a group of zero or more abstract methods• Abstract methods have no default implementation.• Abstract methods are to be implemented in a child class or child struct. • Subclassing an interface by a class or struct is called

implementation of the interface.• An interface can be implemented but not instantiated.

You can’t use an interface class to create an object.• Interfaces can also include properties and events, but no data.• An interface defines a contract between a type and users of that type. Used to define software interface standards.• All interface methods are public, no specifiers needed.• A class can implement multiple interfaces.

Page 20: C# Yingcai Xiao. Part I Moving from Java to C# .NET Framework ’ s Data Types: CTS Six categories of data types in CTS: system-defined: Primitives (int,

Interface ExampleInterface Exampleinterface ISecret {void Encrypt (byte[] inbuf, byte[] outbuf, Key key);void Unencrypt (byte[] inbuf, byte[] outbuf, Key key);} //no implementation, just prototyping.

class Message : ISecret {public void Encrypt (byte[] inbuf, byte[] outbuf, Key key)

{ /* implementation here */ }public void Unencrypt(byte[] inbuf, byte[] outbuf, Key key)

{ /* implementation here */ }}

Message msg = new Message();// e.g. check if object msg implements interface ISecretif (msg is ISecret) { // type checking, // an object of a child type is also an object of the parent type, but not the other way around ISecret secret = (ISecret) msg; // from child to parent, explicit cast secret.Encrypt (...);}

Page 21: C# Yingcai Xiao. Part I Moving from Java to C# .NET Framework ’ s Data Types: CTS Six categories of data types in CTS: system-defined: Primitives (int,

Abstract ClassAbstract Class

• An abstract class is a class that can’t be instantiated, i.e., one can’t use an abstract class to create an object.

• The definition of an abstract class looks like a regular class except the preceding keyword “abstract”.

• It can have member fields and methods. • It can only be used as a base class for subclassing. • Its subclasses can inherit its methods as default implementation. (They can overwrite those methods too.)

• It is not allowed to inherit from multiple abstract classes.

Page 22: C# Yingcai Xiao. Part I Moving from Java to C# .NET Framework ’ s Data Types: CTS Six categories of data types in CTS: system-defined: Primitives (int,

Abstract Class vs. Interface ClassesAbstract Class vs. Interface Classes

• Both can’t be instantiated.• Both defines standards for their subclass to implement.• An abstract class defines the minimal implementation of its subclasses.• An interface has no implementation at all.• A child class can’t subclass from more than one abstract classes. No multiple inheritance for abstract classes.• A child class can implement more than one interfaces. Multiple inheritance allowed for interfaces.• Abstract classes and interfaces can be used together.

Page 23: C# Yingcai Xiao. Part I Moving from Java to C# .NET Framework ’ s Data Types: CTS Six categories of data types in CTS: system-defined: Primitives (int,

Abstract Class & Interface Abstract Class & Interface ExamplesExamplesabstract class DefaultTokenImpl {

private readonly string name;public string ToString() { return name; }protected DefaultTokenImpl(string name){ this.name = name; }

}

interface IToken { string ToString(); } interface IVisitable { void Accept(ITokenVisitor visitor); }interface IVisitableToken : IVisitable, IToken { }

class KeywordToken : DefaultTokenImpl, IVisitableToken {public KeywordToken(string name) : base(name) { }void IVisitable.Accept(ITokenVisitor visitor) {

visitor.VisitKeyword(ToString());}}

Page 24: C# Yingcai Xiao. Part I Moving from Java to C# .NET Framework ’ s Data Types: CTS Six categories of data types in CTS: system-defined: Primitives (int,

Abstract Class & Interface Abstract Class & Interface ExamplesExamples• KeywordToken subclasses the abstract class DefaultTokenImpl

• It also implements the interface IVisitableToken (which implements interfaces IVisitable and IToken)

• It implements the Accept abstract method specified in interface IVisitable (a parent of IVisitableToken)

• It inherits the default implementation of ToString from the abstract class DefaultTokenImpl to implement the ToString abstract method specified in interface IToken (the other parent of IVisitableToken).

Page 25: C# Yingcai Xiao. Part I Moving from Java to C# .NET Framework ’ s Data Types: CTS Six categories of data types in CTS: system-defined: Primitives (int,

ExceptionException

Page 26: C# Yingcai Xiao. Part I Moving from Java to C# .NET Framework ’ s Data Types: CTS Six categories of data types in CTS: system-defined: Primitives (int,

Exception HandlingException Handling

Exception Handling (object-oriented event-driven runtime error handling)• An exception is thrown when a run-time error occurs.• The CLR defines how exceptions are thrown and how they’re handled. (How exception “events” are generated and how they’re handled by exception “event” handlers). • You can throw an exception in any language and catch it in

any other. • You can throw exceptions across machines

Page 27: C# Yingcai Xiao. Part I Moving from Java to C# .NET Framework ’ s Data Types: CTS Six categories of data types in CTS: system-defined: Primitives (int,

Exception HandlingException Handling

CLR’s Exception Handling Mechanism: try, catch, finally, and throw

File file = null; // Do not define it in the try block. Why?try { file = new File ("Readme.txt"); if(file != null) { /* Do the work here. */} … }catch (FileNotFoundException e) { Console.WriteLine (e.Message); }catch ( … ) { … }catch ( … ) { … }}finally { // Always come here even if there were exceptions. if (file != null) file.Close ();}

Page 28: C# Yingcai Xiao. Part I Moving from Java to C# .NET Framework ’ s Data Types: CTS Six categories of data types in CTS: system-defined: Primitives (int,

Exception HandlingException Handling

• The CLR calls the handler that most closely matches the type of exception thrown.• All of the exception types defined in the FCL are derived directly or indirectly from System.Exception.• FCL exception classes contain a Message property, which holds an error

message describing what went wrong, and a StackTrace property, which details the call chain leading up to the exception.

• Exception handlers can be nested.• Code in a finally block is guaranteed to execute, whether an exception is

thrown or not.• An exception that is best handled by the caller rather than the callee.• Programmers can throw exceptions defined in FCL or their own exceptions derived from System.ApplicationException.

if (value > 0) width = value; else throw new ArgumentOutOfRangeException ( "Width can’t be negative.");

Page 29: C# Yingcai Xiao. Part I Moving from Java to C# .NET Framework ’ s Data Types: CTS Six categories of data types in CTS: system-defined: Primitives (int,

System.Object : root class for all other classes.

• Every class inherits the Finalize( ) method from System.Object. • It is called just before an object is destroyed by the garbage collector of CLR.• The time of call is determined by CLR not by the program. • Use System.GC.Collect() to force a garbage collection (system wide, time consuming).

Destructor in C++ is called just before an object is destroyed by the program, when the object is freed (for heap objects) or out of scope (for stack objects).

The Object Class: System.ObjectThe Object Class: System.Object

Page 30: C# Yingcai Xiao. Part I Moving from Java to C# .NET Framework ’ s Data Types: CTS Six categories of data types in CTS: system-defined: Primitives (int,

C# C# Part IIPart II

Beyond JavaBeyond Java

Page 31: C# Yingcai Xiao. Part I Moving from Java to C# .NET Framework ’ s Data Types: CTS Six categories of data types in CTS: system-defined: Primitives (int,

Internal Memory Structures of Data Internal Memory Structures of Data StoreStore

Page 32: C# Yingcai Xiao. Part I Moving from Java to C# .NET Framework ’ s Data Types: CTS Six categories of data types in CTS: system-defined: Primitives (int,

Instantiating a Class (in C++)Instantiating a Class (in C++)

Class Name;

In C++: “Rectangle rect” declares an object of class Rectangle.

int width;int width;

int height;int height;

Rectangle ()Rectangle ()

Rectangle (int w, int Rectangle (int w, int h)h)

……

rect

“rect” is the name of a memory space that stores a Rectangle object.

Page 33: C# Yingcai Xiao. Part I Moving from Java to C# .NET Framework ’ s Data Types: CTS Six categories of data types in CTS: system-defined: Primitives (int,

Instantiating a Class (in CTS)Instantiating a Class (in CTS)

Class Name;

In CTS: “Rectangle rect” declares a reference of class Rectangle.

A reference to a Rectangle A reference to a Rectangle object.object.

rect

A “reference” is an internal pointer, it needs to “point” to an object before being dereferenced.

“rect” is the name of a memory space that stores a reference. This is similar to Java.

Page 34: C# Yingcai Xiao. Part I Moving from Java to C# .NET Framework ’ s Data Types: CTS Six categories of data types in CTS: system-defined: Primitives (int,

ReferencesReferencesRectangle rect;  int area = rect.Area; // will not compile in C# Rectangle rect = new Rectangle (3, 4); // Use the second constructor

int widthint width

Int heightInt height

Rectangle ()Rectangle ()

Rectangle (int w, int Rectangle (int w, int h)h)

AreaArea

rect

0x12345678

• Dereferencing is automatic for a reference. (No *rect or rect->)int area = rect.Area;

0x1234560x1234567878

33

44

Rectangle ()Rectangle ()

Rectangle (int cx, int Rectangle (int cx, int cy)cy)

AreaArea• Please note the notation difference between a “pointer/reference” and a “name” in this lecture.

Page 35: C# Yingcai Xiao. Part I Moving from Java to C# .NET Framework ’ s Data Types: CTS Six categories of data types in CTS: system-defined: Primitives (int,

Value TypesValue Types

int i; In CTS: is i a reference to an integer or just an integer?In CTS: i is an int (a system defined primitive type),

not a reference to an integer. “i” is the name of a memory space that stores an integer value.

int i = 8;

i is a value type, for which we can directly store an integer value into the memory named as i. Compiler already allocated memory to store the value and we don’t need to “new” to allocate memory to store the value.

88i

Page 36: C# Yingcai Xiao. Part I Moving from Java to C# .NET Framework ’ s Data Types: CTS Six categories of data types in CTS: system-defined: Primitives (int,

Value TypesValue Types

Fields of value types have the object (not reference) memories allocated by the compiler and can be used as an object directly without “new”.

Can we define user types behave like value types?

Class is used to define user types, but need to be “new”ed before using. Memories are allocated at runtime. => Tedious and Slow.

Page 37: C# Yingcai Xiao. Part I Moving from Java to C# .NET Framework ’ s Data Types: CTS Six categories of data types in CTS: system-defined: Primitives (int,

StructsStructs

Structs: user-defined value types, less overhead and easier to use than classes.struct Point{ public int x; public int y;

public Point () {x = 0 ; y = 0; } public Point (int x, int y) { this.x = x; this.y = y; }}

Point pnt1; // pnt1 is an object, not a reference. x = 0, y = 0 Point pnt2= new Point (); // pnt2 is an object, not a reference. x = 0, y = 0Point pnt3 = new Point (3, 4); // pnt3 is an object, not a reference. x = 3, y = 4// The compiler uses “new” to initialize an object. Point pnt4(3,4); is not allowed in CTS.

Page 38: C# Yingcai Xiao. Part I Moving from Java to C# .NET Framework ’ s Data Types: CTS Six categories of data types in CTS: system-defined: Primitives (int,

Summary: Value and Reference Summary: Value and Reference Types in CTSTypes in CTS

In CTS, Value Types are Stack Objects: memory allocated at compile time on the stackauto destruction, no garbage collection neededless overhead, code runs fasterless flexible, sizes need to be known at compile time

In CTS, Reference Types are Heap Objects: memory allocated at run time on the heapgarbage collected more flexible, sizes need not to be known at compile timemore overhead, code runs slower

Class defines reference types (heap objects)Struct defines value types (stack objects), even though “new” is used to create struct objects. Value types can’t derive from other types except interfaces.

Page 39: C# Yingcai Xiao. Part I Moving from Java to C# .NET Framework ’ s Data Types: CTS Six categories of data types in CTS: system-defined: Primitives (int,

Class CodeClass Codeclass Point{ public int x; public int y;}Point p1 = new Point ();p1.x = 1;p1.y = 2;Point p2 = p1; // Copies the underlying pointerp2.x = 3;p2.y = 4;Console.WriteLine ("p1 = ({0}, {1})", p1.x, p1.y); Console.WriteLine ("p2 = ({0}, {1})", p2.x, p2.y); Point p3; p3.x = 5; p3.y = 6;

Page 40: C# Yingcai Xiao. Part I Moving from Java to C# .NET Framework ’ s Data Types: CTS Six categories of data types in CTS: system-defined: Primitives (int,

Class CodeClass Codeclass Point{ public int x; public int y;}Point p1 = new Point ();p1.x = 1;p1.y = 2;Point p2 = p1; // Copies the underlying pointerp2.x = 3;p2.y = 4;Console.WriteLine ("p1 = ({0}, {1})", p1.x, p1.y); // Writes "(3, 4)"Console.WriteLine ("p2 = ({0}, {1})", p2.x, p2.y); // Writes "(3, 4)"Point p3;//Creats a reference(pointer), no memory allocated p3.x = 5; // Will not compilep3.y = 6; // Will not compile

Page 41: C# Yingcai Xiao. Part I Moving from Java to C# .NET Framework ’ s Data Types: CTS Six categories of data types in CTS: system-defined: Primitives (int,

Struct CodeStruct Codestruct Point{ public int x; public int y;}Point p1 = new Point(); //Creates a value object on stack.p1.x = 1;p1.y = 2;Point p2 = p1;//Makes a new copy of the object on the stackp2.x = 3;p2.y = 4;Console.WriteLine ("p1 = ({0}, {1})", p1.x, p1.y); // Writes "(1, 2)"Console.WriteLine ("p2 = ({0}, {1})", p2.x, p2.y); // Writes "(3, 4)"Point p3; //Creates a value object on the stackp3.x = 5; // It works.p3.y = 6;Console.WriteLine ("p3 = ({0}, {1})", p3.x, p3.y); // Writes "(5, 6)"

Page 42: C# Yingcai Xiao. Part I Moving from Java to C# .NET Framework ’ s Data Types: CTS Six categories of data types in CTS: system-defined: Primitives (int,

int a[2]; a[0] = 5; a[1] = 10;// stack objects, size has to be known at compile time and can’t be changed at runtime.

int size = 2;int *p; // a pointerp = new int[size]; p[0] = 5; p[1] = 10;// heap objects; dynamically allocated at runtime, “size” can be a variable

delete p; // free the memory.

55 1010

55 10100x0x

a

p

Arrays in C++Arrays in C++

Page 43: C# Yingcai Xiao. Part I Moving from Java to C# .NET Framework ’ s Data Types: CTS Six categories of data types in CTS: system-defined: Primitives (int,

Arrays in CTSArrays in CTS

Array (same syntax for both class and struct):Point[] pa = new Point[2];pa[0] = new Point();pa[1] = new Point();Console.WriteLine ("pa[0] = ({0}, {1})", pa[0].x, pa[0].y); Console.WriteLine ("pa[1] = ({0}, {1})", pa[1].x, pa[1].y);

Challenges: (1) Draw pictures to show the memory layout of pa for Point as a

class and a struct.(2) What will happen when lines 2 and 3 are removed. Explain what will happen for Point as a class and then as a struct.

Page 44: C# Yingcai Xiao. Part I Moving from Java to C# .NET Framework ’ s Data Types: CTS Six categories of data types in CTS: system-defined: Primitives (int,

Generics : parameterized types

According to Microsoft (http://msdn2.microsoft.com/en-us/library/512aeb7t(VS.80).aspx)• Use generic types to maximize code reuse, type safety, and performance.• The most common use of generics is to create collection classes.• The .NET Framework class library contains several new generic collection classes in the System.Collections.Generic namespace. These should be used whenever possible in place of classes such as ArrayList in the System.Collections namespace.• You can create your own generic interfaces, classes, methods, events and delegates.• Generic classes may be constrained to enable access to methods on particular data types.• Information on the types used in a generic data type may be obtained at run-time by means of reflection.

C# and CLR GenericsC# and CLR Generics

Page 45: C# Yingcai Xiao. Part I Moving from Java to C# .NET Framework ’ s Data Types: CTS Six categories of data types in CTS: system-defined: Primitives (int,

The Fundamentals C#The Fundamentals C#

Basic CTS Types: Class, Struct, Enum, Property, Event, Delegate, Value Type, Reference Type, Basic .NET Concepts: Garbage Collection, DLL, Versioning, Strong Name, GAC, Exception Handling, Try, Catch, Finally, Throw.

What is it? How to define and use it? Can you write a program?Can you trace a program? Do you know what going on inside?