Object Oriented
Programming
with .Net Core, C#
Prof. Dr. Aydın SEÇER
Basics and Data Types-1
• Structure Of A C# Program
• Keywords
• What is Re-Sharper
• Data Types
• Variables and their definitons
• var (anonymous) and dynamic keywords
• Constants
• Readonly keyword
• Overflow
• Scope Rule
• Comments
• Input and output methods
Basics and Data Types-2
• Type Conversion
Imlicit
Explicit
• Boxing and Unboxing- (will be discussed in Future)
• Operators:
Arithmetic
Relational
Logical
Bitwise
Assingment
Unary
Ternary, conditional
Operator overloading (will be discussed in Future)
Basics and Data Types-3
• «sizeof()», «typeof()», «is» and «as» operatosArray Basics
Arrays of primitive types,
2D and higher dimensional arrays
NULL type (‘\0’ macro in C, Null Reference in C#, only reference types can be null)
Conditional Statements
if, if…else if, else
switch, case
Conditional if, val1==val2 ? if-true : if-false
Control Flows and Loops
for,
foreach
while
Do.. while
goto,
Infinite loops
Recursive functions (will be discussed in Future)
break and continue keywords.
String Type
• String in memory
• String is immutable
• String is reference type, string is a class
• Char Array vs String
• Char Array is Mutable
• String Comparision, S
• String arrays
• Some useful string methods, String.Format() method, @ and $ symbol usage in strings
• StringBuilder Class (will be discussed in Future)
MEMORY
Methods (Functions) in OOP
• Defining a method
• Method Types according to signature
void MethodName(void)
type MethodName(void)
type MethodName(type)
void MethodName(type)
Constructor methods (will be discussed in Future)
Destructor (finalizer) methods (will be discussed in Future)
Extension Methods (will be discussed in Future)
Constructor methods (will be discussed in Future)
Asyncronous Methods (will be discussed in Future)
Anonymous Methods (will be discussed in Future)
Optional Parameters in methods: MethodName (int x =1)
Methods with variable number parameters: MethodName (string[] args) or int[] args…
Calling methods with random order parameters MethodName(x:1,y:2)
Methods which can return object(will be discussed in Future)
Methods which can get object parameters (will be discussed in Future)
Method overloading
Methods which arguments are methods/callback (advanced) (will be discussed in Future)
Some useful built-in classes, structs
• Random class
• DateTime struct
• TimeSpan struct
• Math class
• Convert class
Grouping Code Blocks
• #region ….#endregion blocks
Introduction to Object Oriented
Programming
OOP
Class and class members
• Class definition
Class is a template for object definition
Provides details of any real world object
Class Members
Fields
Properties
Methods
Constructor methods: default and overloaded constructors
Destructor method : ~classname()
Indexers
Creating (getting instance) object by new keyword
Object initializers
Constructor methods and new keyword relation
Instance members vs static members
Garbage collector
Finalize() method
Dispose() method
~classname() method
Class vs Object
• Class is definiton or template of any object
• Class does not mean object directly (object != class)
• Object is created from class
• Created by using new «new» keyword
• new keyword calls class constructor methods
• Constructor method creates object and store it in the memory
• Object is a variable of class (class members)
• Object is an instance of class
OOP Concepts-1 Encapsulation
• Encapsulation
Data hiding
Data packaging
Capsule of class members for visibility
Capsule like medicine tablet to protect members from outside the world
Access modifiers for encapsulation
Public (Accessed From Everywhere)
Protected (Accessed From Base and Derived Class)
Private (Accessed From Class itself)
Internal (Accessed From Same Assembly)
Protected internal (Accessed from same assebmly and derived class)
Access modifiers usage
All class members
Classes
Interfaces
Structs
Enumerators
Access Modifiers
Same assembly olduğunda
Internal gibi davranır,
outside assembly olduğunda
protected gibi davranır
derived class ise same assembly
Yes ise Yes
OOP Concepts-2 Inheritance
• Inheritance
• Application of Inheritance
• Access Modifiers and Inheritance
• Virtual Methods (can be overriden in children)
• Hide methods and new keyword
• Inhertiance and Overloaded Constructors
• Inheritance Types
Single Inheritance
Multilevel Inheritance
Hierarchical Inheritance
Multiple Inheritance (Through Interface)
Hybrid Inheritance(Through Interface)
OOP Concepts-3 Abstraction
• Interfaces
Is data contract for objects
Hiding details, only contracts
It fully abstract
Is not a class
Only contains signature of methods,properties, events or fileds
It can be inherited by only interfaces
It can be implemented by classes
• Inhertiance vs Implemantation
• Abstract Classes
Abstract Methods
Concrete Methods
sealed override methods
Interface vs Abstract Class
Interface vs Concrete Class
Abstract Class vs Concrete Class
A class only inherits one base, but can implement multiple interface ***
Interfaces supports multiple inheritance from other interfaces ***
OOP Concepts-4 Polymorphism
• Polymorphism
• Virtual methods revisited
• Method override
• Example of polymorphism
Type of Classes
• Regular Class
• Abstract Class
• Static Class
• Sealed Class
• Partial Class
Struct Data Type
• Struct looks and acts like a class
• Struct is value type, not reference type
• Can have, fields, properties, methods and events
• Can implement interfaces
• Can be used without new keyword (But field must be initilized)
• Can be instantiated with new keyword
• Cannot have default constructor but overloaded is possible
• All fields must be intialized from overloaded constructors
• Not support inheritance both from class and struct
Struct Example
• Ref vs value type
Extension Methods, Operator
Overloading
• Extension Methods
• Operator Overloading
• Anonymous Types
var emp2 = new { EmployeeID = 1, Name = "Demo", Salary = 100000 };
Console.WriteLine(emp2.EmployeeID);
Console.WriteLine(emp2.Name);
• Tuples
var t2 = Tuple.Create(1, 2, 3, 4, 5, 6, 7, Tuple.Create(11, 21, 31));
Console.WriteLine(t2.Rest.Item1.Item1 + " " + t2.Rest.Item1.Item2 + " " +
t2.Rest.Item1.Item3);
Operator Overloading Example of
Point Class
Complex Number Example
Boxing and Unboxing
• Boxing and Unboxing have performance issue!!!
• Boxing
Object o1 = student;
• Unboxing
var student1 =(Student)o1
Assemblies and Namespaces
• Assembly
• Namespace
Framework namespaces
Namespaces prevents name conflicts for objects
Aliases
.(dot) operator
(global::) prevents name conflicts of namespaces.
Framework Defined Useful Interfaces
• INotifyPropertyChanged
• IComparable interface
• IComparable <T> generic interface
• IComparer interface
• IComparer <T> generic interface
• IEquitable <T> generic interface
GetHashCode () can be used
• IEqualityComparer <T> generic interface
• IEnumerable interface
Can be used with foreach loop for a class that contains array data
• IEnumerator and IEnumerator <T> generic interface
Can be used with foreach loop for a class that contains array data
• IEnumerable <T> generic interface
Can be used with foreach loop for a class that contains array data
• ICollection interface
Can be used with foreach loop for a class that contains array data
• ICollection <T> generic interface
Can be used with foreach loop for a class that contains array data
INotifyPropertyChanged
IComparable and IComparable <T> generic
interface
IComparer and IComparer <T> generic interface
IEquitable <T> generic interface
IEqualityComparer and IEqualityComparer <T>
generic interface
IEnumerator and IEnumerator <T> generic
interface
IEnumerable and IEnumerable <T> generic
interface
ICollection and ICollection <T> generic interface
Collections
• Nongeneric Collectons (All of them need casting op…)
Array List
Sorted List / Key based auto sorting
Dictionary
HashTable
Queue
Stack
• Generic Collections (No need cast op..)
List<T>
SortedList<TKey,TValue>
Stack<T>
Queue<T>
Dictionary<Tkey, Tvalue)
HashSet<T>
SortedSet<T>
LinkedList<T>
KeyValuePair<TKey, TValue>
Custom Tree<T>
Custom Graph<T>
Template Types
and Methods
• Generic Class
• Generic Method
About Generic Types
• Collections that are type-safe at compile time
• Faster Collection types
• Can be applied for classes and methods as template
• No need BOXING, and UNBOXING operations
Exception Handling
• Try and catch block
• Multiple catch blocks
• Finaly block
• Exception base class
• Exception types
• Custom exceptions
• Throw keyword
IO and Stream
• System.IO.Directory class • Binary Writer
• System.IO.File class • Buffered Sream
• DirectoryInfo Class • Stream Reader
• FileInfo Class • Stream Writer
• DriveInfo • FileStream
• Text Reader • FileSystemInfo
• Text Writer • FileSystemWatcher
• Binary Reader • MemoryStream
• Path
Delegates and Events
Delegates
• Delegates are method pointers
• Generic and Nongeneric Delagates
• References methods
• Can be used like variable
Returning Methods as Parameter
Multicast
Delagates
.Net Generic Delegates
• Action
• Func
Action Generic
Delegate
Func Generic
Delegate
Lambda
Expression
• You can write methods
• Everywhere
In methods
As method parameters
Events
Add or Remove Event Bindings
• instanceObject.someEvent += anyhandler; //ADD handler
• instanceObject.someEvent -= anyhandler; //REMOVE handler
CPU
Process
Multi Threading
CPU, Process and Threads
Process
• A running instance of any program
• Can be seen from task manager
in Windows
• Every process has its own memory address
space (execution environment) and it is in
that all the data and the instructions of
that process reside.
• A process has a self-contained execution
environment.
• A process generally has a complete, private set of basic run-time resources;
in particular, each process has its own memory space
Threads
• The path of execution of instructions within a process is called a thread.
• It has a starting point, execution sequence and terminating point.
• Thread is a specific work piece or task piece
• Independent execution path in a program
• Used to perform multiple tasks at the same time as parallel, or asyncronous
• Single Threaded process
One thread
• Multi Threaded process
Multiple thread
• Main Thread of a program, every program must have at least one thread.
Multithreading & Multiprocessing
Multithreading Multiprocessing/Multitasking
Multithreading is the ability of an
Multitasking is the ability of an operating
operating system to execute the different
system to accommodate more than one
parts of the program, called threads,
program in the memory at the same time.
concurrently.
In multithreading all threads share same
Processes do not share the memory
process address space [memory].
External resources like file system or
database must be used for communication
Threads can share variables since threads
between multiple processes and each one
are in same process.
runs under its unique process address
space.
Inter thread communication is simple Inter process communication is complex
Less resources required to launch/run
CPU has to spend more resources for
them since they are part of an already
launching a new process hence process is
running process, hence they are called as
known as heavy weight.
light weight tasks.
Example of some Multithreading
Applications
• MS-Word – Auto Saving, Spell Checking, Printing while editing
• VS.NET – Intellisense, Auto Compilation.
• Browser – Downloading multiple files and browsing simultaneously.
• Media Player – Movie and Sound
• and so on ….
• ….almost all program is multithread
Process vs Thread
Main Thread and Child Tread
Important Notes
• The process terminates when the main thread terminates.
• A thread terminates only when the other non-background threads which
it has created terminates.
• The creator doesn’t wait for the background thread if it has to terminate.
Thread Operations
• Start(), Start(params) starts the thread
• Thread.Sleep(miliseconds) pauses tastk, that is in contained thread
• Join(): If a thread executes t.Join() the current thread state is changed to waiting and
it remains in that state until the thread referred by “t” is terminated.
• Join(3000): The current threads waits for a max of 3000 milliseconds and then would
resume automatically.
• IsAlive() : To check if the thread is dead or alive.
• Thread.CurrentThread : To Get the reference of the current thread.
• t.ThreadPriority = ThreadPriority.Highest.
• Abort(): To stop the thread. When the Abort() method is called on a thread it throws
ThreadAbortException irrespective of its state. If this exception is unhandled the
thread terminates, and if it is handled and if Thread.ResetAbort() is executed the
thread is not aborted and would continue normal execution.
• IsBackground: When a thread is created as background thread, the creator thread
does not wait for the background thread to terminate or join the creator thread. The
background thread is automatically aborted when the creator thread aborts.
Thread Lifecycle
Join( ) example
Thread States and properties
• IsAlive
• Priority
• IsBackgroud
• ThreadState
Running
Stopped
Aborted
Suspended
Unstarted
Thread Priority
Thread Pool
• A thread pool is a collection of threads that can be used to perform a number of
tasks in the background.
• Thread pools are often employed in server applications.
• Each incoming request is assigned to a thread from the thread pool, so the request
can be processed asynchronously, without tying up the primary thread or delaying
the processing of subsequent requests.
• Once a thread in the pool completes its task, it is returned to a queue of waiting
threads, where it can be reused.
• This reuse enables applications to avoid the cost of creating a new thread for each
task
• Thread pools typically have a maximum number of threads.
• If all the threads are busy, additional tasks are placed in queue until they can be
serviced as threads become available.
Application of Thread Pool
Foreground and Background Threads
• Foreground Thread
Foreground threads are those threads that keep
running even after the application exits or quits.
It has the ability to prevent the current application
from terminating.
The CLR will not shut down the application until all
Foreground Threads have stopped.
• Background Thread
Background Threads are those threads that will quit if
our main application quits. In short, if our main
application quits, the background thread will also quit.
Background threads are views by the CLR and if all
foreground threads have terminated, any and all
background threads are automatically stopped when
the application quits.
Thread Synchronization, Thread safe
classes and operations
• Requirement: In situation where one object is shared by more than one thread, if
the thread has to modify the state of the object it should ensure that only one thread
does so at a given instance of time.
• Critical Section is a block of code which can be executed by only one thread at any
given instance of time.
• If there are two threads executing on same shared object then both the threads can
execute some method on the object at the same point of time and if they then change
the state of the object, it may result in ambiguity of data causing Threads De-
Synchronization. To avoid this we use lock block.
//Monitoring object by lock keyword In C#
lock(object)
{
//……. modify object here
}
Monitoring object by lock keyword in C#
• ***Managed by single process, does not
affects between different processes
• Monitor(lock) is a .Net specific object and is local to a
given process and thus it cannot be used for
synchronizing threads running in different
processes
Mutex class for Thread
• ***Managed by Operating System, can be used one mutex between
different processes
• It is a synchronization resource managed by the OS. Thus it can be
used for synchronizing threads running in different processes.
Semaphore class for Thread
• Semaphore is used for synchronizing
threads.
• Within same process or in different
process.
• Works exactly like Mutex but has a
facility to allow more than one
thread (but a pre-defined count) to
execute a given block at the same
time.
• Mutex can be treated as a special
case of semaphore where count = 1.
Task Parallel Library
• Types of TPL: Task Parallelizm and Data Parallelizm
• The Task Parallel Library (TPL) is a set of public types and APIs in the System.Threading and
System.Threading.Tasks.
• The purpose of the TPL is to make developers more productive by simplifying the process of adding
parallelism and concurrency to applications.
• The TPL scales the degree of concurrency dynamically to most efficiently use all the processors that are
available.
• In addition, the TPL handles the partitioning of the work, the scheduling of threads on the ThreadPool,
cancellation support, state management, and other low-level details.
• By using TPL, you can maximize the performance of your code while focusing on the work that your
program is designed to accomplish.
• Note: However, not all code is suitable for parallelization; for example, if a loop performs only a small
amount of work on each iteration, or it doesn't run for many iterations, then the overhead of
parallelization can cause the code to run more slowly.
• Parallelization like any multithreaded code adds complexity to your program execution.
• Data parallelism refers to scenarios in which the same operation is performed concurrently (that is, in
parallel) on elements in a source collection or array. In data parallel operations, the source collection is
partitioned so that multiple threads can operate on different segments concurrently.
System.Threading.Tasks.Parallel
• Parallel.For
• Parallel.ForEach
• Parallel.Invoke
Task Class
• Like thread executed parallel
• Task.WaitAny(,,,,)
• Task.WaitAll(,,,)
• Task.WhenAll(,,,)
• Like background thread
• Task task; task.Start(…);
• Task.Factory.StartNew(…) for direct
create and start in one line.
• Task task; task.ContinueWith(…);
• :……..
Concurrent Collections, Thread Safe Objets
• using System.Collections.Concurrent;
• ConcurrentDictionary<int, string> numbers = new ConcurrentDictionary<int, string>();
• ConcurrentStack
• ConcurrentQueue
• Etc……
Asynchronous Programming
• Using previous technique discussed in this lecture is hard to develop
asynchronous programming.
• But, Asynchronous Programming has positive sides:
• Overcome performance issues
• Easy to debug
• Easy to write
• Easy to maintain
• Can be executed as synchronously by await keyword
async/await keywords
Signaling in Asynchronous Programming
Cancellation Tokens in Async methods
Reflection in C#
Type Class
Activator Class
From full qualified assembly name
Predefined Attributes
• Obsolete Attribute
• Conditional Attribute
Custom Attributes
Garbage Collection
Data Security
New features in C#
Debugging Applications, Debugging Tools Call
Stack Window, Locals and Autos Windows
LINQ (Language Integrated Query)
Some Revisited Topics
• Nullable Types
• Dynamic vs Static Keywords
• Reference vs Value Types
• Stack and Heap
• Compile Time vs. Runtime Errors
Working with XML
ADO.Net
Entity Framework
Refactoring C# Code
Defensive Coding
Design Patterns
Dependency Injection
Unsafe code and pointers
Working with Culture & Regions
Regular Expressions (Regex)
String, StringBuilder in C#
Association between Classes