Top Banner
CSE 136 Lecture 3 Part 1 Introduction to C# language Memory Management Static vs non-static Properties Inheritance Modifiers (public, private, protected, etc) Namespace and Assembly (dll, exe)
57
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Day3

CSE 136 Lecture 3 Part 1

Introduction to C# language Memory Management Static vs non-static Properties Inheritance Modifiers (public, private, protected, etc) Namespace and Assembly (dll, exe)

Page 2: Day3

Overview

Hide/Show studentsemail address

Pass students databetween web and

business logic layer

Data TransferObject...

(more on this later)

Business Object:student's enrollment

info

Object to RelationalModel...

(more on this later)

All usingC# Language and

.NET libraries

Page 3: Day3

C# Simple Program

Class namedConsole

Inside the class, amethod name called

WriteLine()

Namespace is like apackage in JAVA

Page 4: Day3

C# keywordsSimilar to Java

Page 5: Day3

C# Pre-defined types

Page 6: Day3

C# type values range

int intValue = 100; System.Int32 intValue = 100;=

Page 7: Day3

Stack Memory

The values of certain types of variable

value types: int,float, bool, char,

etc

The program's current executionenvironment

(inside a method)int x;int y;

Parameters passed to the methods sum = Add(1, 5)

1000

Starting at byte address1000

32-bit wide each box4-byte wide each box

996 Push 13,456 to the stack

992 Push 562 to the stack

Page 8: Day3

Heap Memory

not usedanymore

CLR

CLR - commonlanguage runtime

more memoryavailable

Page 9: Day3

Value Type vs Reference Type

Page 10: Day3

Value Types on Stack

Local Variables

Save on the stack

1000

Actual value goeson the stack

996

992

988

reference addressgoes on the stack(not actual value)

984

Page 11: Day3

Class Type

NewInstance

What's the difference between a class and an object?

Class : a user-defined type (declaration)

Object : an instance of a class (exist in memory)

Page 12: Day3

Class Type and Heap

Initialized

High = 0Low = 0

Page 13: Day3

Boxing

Boxing - takes a value type value, creates from it a fullreference type object in the heap, and returns areference to the object

value type

full objectreferencereturn reference

Page 14: Day3

Unboxing

Unboxing is the process of converting a boxed objectback to its value type

oi - boxed object

(int) - unboxing

Why box/unbox?Pass variables to method as reference

Page 15: Day3

Value Parameter

Allocates space onthe stack for theformal parameter

Copies the actualparameter to theformal parameter

x = 5passed in

valuecopied

x value notchanged

Page 16: Day3

Reference Parameter

Keyword is "ref"

The actual parametermust be a variable(i.e "x", not "5")

Must assign areference value(null ok)

value changed

box/unbox concept

Page 17: Day3

Out Parameter

Keyword is "out"

out

out

The actual parametermust be a variable(i.e "y", not "10")

Must assign avalue in themethod call.

Page 18: Day3

Static Field

static

Static field is shared by all the instances of the class

With a static field, all the instances access the same memorylocationIf the value of the memory location is changed by oneinstance, the change is visible to all the instances

no instance required

Page 19: Day3

Static Function Members

Static function members, like static fields, areindependent of any class instance. Even if there areno instances of a class, you can call a static method.

static function

Use dot-syntaxnotation

interview question: Static function members cannotaccess instance members. They can, however,access other static members

Page 20: Day3

Const field vs Static field

Constants are like Statics

Visible to every instance of the class

Available if there are no instances of the class

Note:Compiled time. Can'tchange it, not even

with constructor

Page 21: Day3

Properties

Property:Hours

A property is often associated with a field (i.e. seconds)

encapsulate a field in a class by declaring it private

public property to give controlled access to thefield from outside the class

You may put if/else &other logics for

properties just like afunction

How do you create a read-only property?

remove the"set" portion

Page 22: Day3

Constructor

Constructorcan haveparameters

Can beoverloaded

Callingconstructors

Same method nameDifferent param types

Page 23: Day3

Static Constructor

static varInitialize the staticfields of the class(RandomKey)

Initializing

Calling the static method

Page 24: Day3

Destructor

You can only have one single finalizer per class

A finalizer cannot have parameters

A finalizer only acts on instances of classes (no staticfinalizer)

A finalizer cannot be called explicitly by your code

It is called in the garbage collection process when your class is nolonger accessible

Garbage collectionbackground process

example:

class1 obj = new class1();

... (some code)

obj.Dispose();obj = null;

Marks the memory asdirty and ready to becleaned

Page 25: Day3

Inheritance - Concept

Base Derived

Derived classhas access tobase public

and protectedmethods/fields

Object re-use

Page 26: Day3

Inheritance - Casting

derived.Print();

gives a referenceto the base class

mybc.Print();

Page 27: Day3

Inheritance - virtual & override

Same access levelSame method name

Same signature (void)

Page 28: Day3

Inheritance - Class Object

In .NET, ALL classes are derived from class "object"

Explicitly derives from object Implicitly derives from object

Commonly used methods:

Equals(Object) - Determines whether the specified Object is

equal to the current Object

ToString() - Returns a string that represents the current

object

GetType() - Gets the Type of the current instance.

GetHashCode() - Serves as a hash function for a particular type.

Page 29: Day3

Constructor and inheritance

Constructor Execution

1. Initialize declaredvariables in the class

2. (base)

3. Constructor's Code

Constructor Initializers

Constructor can be overloaded

base class might have more than one constructor multipleconstructorsin base class

specify whichconstructor by

parametersConstructor's Code

Page 30: Day3

Modifier

Internal

A class marked internal can be seen only by classes within itsown assembly (class library, ex: DLL)

This is the default accessibility levelnot

accessible

Provide code security

Assembly: Dll, Exe(Output of VS project)

Page 31: Day3

Modifier and inheritance

Page 32: Day3

Assembly and namespace

Namespace is a collection of names wherein each name is unique ex: names CSE136.students ex: names CSE136.notes

Assembly is an output unit (dll, exe). An assembly can contain multiple

namespaces ex: CSE136.dll

Page 33: Day3

Review question

How many bits is type int Does stack store type struct Where is type class data stored (stack or

heap)? Where is static class data stored? Is string a value type? Difference between ref and out? Difference between static and const? Difference between public and protected? Difference between override and overload?

Page 34: Day3

Break

Page 35: Day3

CSE 136 - Lecture 3 Part 2

Abstract Class Interfaces Generics Collections Enumeration

Page 36: Day3

Abstract Class

Can be used only as the base class of another class. Abstract classes aredesigned to be inherited from

You cannot define variables or create instances of an abstract class.

Invalidcode

Page 37: Day3

Sealed

The opposite of abstract class

Instantiated as a stand-alone class

Cannot derive from a sealed class

Page 38: Day3

Interface 1

Reference type that represents a set of functionmembers, but does not implement them.

Classes (and structs) can implement interfaces.

definition only

class implementsthe interface

methodimplementation

Similar to abstract classwithout the method implementation

Page 39: Day3

Interface 2

There are no multiple classes inheritance in C#.You may achieve this using interfaces.

2 interfaces

multipleinheritance

Implementations

MyData mem1 = new MyData();mem1.SetData(5);int y = mem1.GetData();

Page 40: Day3

Interface 3 - Polymorphism

Animal[] animals = new Animal[3];

animals[0] = new Cat();

animals[1] = new Bird();

does notimplementILiveBirth

animals[2] = new Dog();

foreach (Animal a in animals){

ILiveBirth b = a as ILiveBirth; if (b != null)

Console.Writeline("Name is " + b.BabyCalled());}

Multiple forms(Method overriding)

Page 41: Day3

Interface 4 - Polymorphism

Animal[] animals = new Animal[3];

animals[0] = new Cat();

animals[1] = new Bird();

no interface

animals[2] = new Dog();

foreach (Animal a in animals){

ILiveBirth b = a as ILiveBirth; if (b != null)

Console.Writeline("Name is " + b.BabyCalled());}

Name is Kitten

OUTPUT :

(b == null)Name is Puppy

Animal takes on multiple forms

ILiveBirth takes on multiple forms

Page 42: Day3

Generics 1

classA a = new classA()class classA{ ... }

Page 43: Day3

Generics 2

T can be any typeint, float, string, etc.

T1, T2 can be any typeint, float, string, etc.

Page 44: Day3

Generic 3

Creating a ConstructedType

Compile time(TYPE SAFE)

Page 45: Day3

Generic 4

Creating Variables and Instances

Using a constructed type to create a reference and an instance

generic classdeclaration

allocate classvariable

allocateinstance

Page 46: Day3

Generic 5

Two constructed classes created from a generic class

compile time

compile time

Page 47: Day3

Generic 6

MyStack<int> stack = new MyStack()<int>;stack.Push(1);stack.Push(3);int x = stack.Pop(); // x = 3int y = stack.Pop(); // y = 1

You can also use:MyStack<string>Mystack<float>

Page 48: Day3

Collections 1

Using List to store string data

output:TyrannosaurusAmargasaurusMamenchisaurusDeinonychusCompsognathus

Page 49: Day3

Collections 2

List can also be used as a list of int

output:237

Page 50: Day3

Collections 3

Using Stack of string

output:fivefourthreetwoone

output:Popping fivePeek at next time to destack: 4Popping '4'

Page 51: Day3

Collections 4

Dictionary<string, int> d = new Dictionary<string, int>();d.Add("cat", 2);d.Add("dog", 1);d.Add("llama", 0);d.Add("iguana", -1);

foreach (KeyValuePair<string, int> pair in d) {

Console.WriteLine("{0}, {1}", pair.Key, pair.Value); }

output:cat, 2dog, 1llama, 0,iguana, -1

Dictionary- Another generic collection type

Page 52: Day3

Enumeration 1

How is this possible?

GetEnumerator()returns an

instance of anenumerator

Iterator Pattern (Design Pattern)

Page 53: Day3

Enumeration 2 - IEnumerator interface

Using the IEnumerator Interface Remember"interface"?

The IEnumerator interface contains three function members

Current is a property that returns the item at the current position in the sequence.

MoveNext is a method that advances the enumerator’s position to the next item inthe collection.

Reset is a method that resets the position to the initial state

You must implement thesethree methods when defining

an enumerator

ordered list

Page 54: Day3

Enumeration 3 - interface

3 methods

constructorpopulates

internal array

1 method

foreach depends onthe enumerable which

calls enumerator

Page 55: Day3

Review question

Difference between abstract class and interface?

Difference between inheritance and polymorphism?

What is type safe? Is generic type safe? Difference between enumerable and

enumerator?

Page 56: Day3

Your assignment

Finish your DB design and stored procedures based on your UML diagram

Demo to TA by Thursday end of class (25% late penalty will apply for late turn-ins)

Page 57: Day3

References

.NET : Architecting Applications for the Enterprise

C# Illustrated