Upload
madamewoolf
View
102
Download
1
Tags:
Embed Size (px)
Citation preview
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)
Overview
Hide/Show studentsemail address
Pass students databetween web and
business logic layer
Data TransferObject...
Business Object:student's enrollment
info
Object to RelationalModel...
All usingC# Language and
.NET libraries
C# Simple Program
Class namedConsole
Inside the class, amethod name called
WriteLine()
Namespace is like apackage in JAVA
C# keywordsSimilar to Java
C# Pre-defined types
C# type values range
int intValue = 100; System.Int32 intValue = 100;=
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
Heap Memory
not usedanymore
CLR
CLR - commonlanguage runtime
more memoryavailable
Value Type vs Reference Type
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
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)
Class Type and Heap
Initialized
High = 0Low = 0
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
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
Value Parameter
Allocates space onthe stack for theformal parameter
Copies the actualparameter to theformal parameter
x = 5passed in
valuecopied
x value notchanged
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
Out Parameter
Keyword is "out"
out
out
The actual parametermust be a variable(i.e "y", not "10")
Must assign avalue in themethod call.
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
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
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
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
Constructor
Constructorcan haveparameters
Can beoverloaded
Callingconstructors
Same method nameDifferent param types
Static Constructor
static varInitialize the staticfields of the class(RandomKey)
Initializing
Calling the static method
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
Inheritance - Concept
Base Derived
Derived classhas access tobase public
and protectedmethods/fields
Object re-use
Inheritance - Casting
derived.Print();
gives a referenceto the base class
mybc.Print();
Inheritance - virtual & override
Same access levelSame method name
Same signature (void)
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.
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
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)
Modifier and inheritance
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
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?
Break
CSE 136 - Lecture 3 Part 2
Abstract Class Interfaces Generics Collections Enumeration
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
Sealed
The opposite of abstract class
Instantiated as a stand-alone class
Cannot derive from a sealed class
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
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();
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)
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
Generics 1
classA a = new classA()class classA{ ... }
Generics 2
T can be any typeint, float, string, etc.
T1, T2 can be any typeint, float, string, etc.
Generic 3
Creating a ConstructedType
Compile time(TYPE SAFE)
Generic 4
Creating Variables and Instances
Using a constructed type to create a reference and an instance
generic classdeclaration
allocate classvariable
allocateinstance
Generic 5
Two constructed classes created from a generic class
compile time
compile time
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>
Collections 1
Using List to store string data
output:TyrannosaurusAmargasaurusMamenchisaurusDeinonychusCompsognathus
Collections 2
List can also be used as a list of int
output:237
Collections 3
Using Stack of string
output:fivefourthreetwoone
output:Popping fivePeek at next time to destack: 4Popping '4'
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
Enumeration 1
How is this possible?
GetEnumerator()returns an
instance of anenumerator
Iterator Pattern (Design Pattern)
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
Enumeration 3 - interface
3 methods
constructorpopulates
internal array
1 method
foreach depends onthe enumerable which
calls enumerator
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?
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)
References
.NET : Architecting Applications for the Enterprise
C# Illustrated