0% found this document useful (0 votes)
6 views89 pages

04 C Advanced Features New

Uploaded by

xhonatan.naumi16
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views89 pages

04 C Advanced Features New

Uploaded by

xhonatan.naumi16
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 89

C# - Advanced Features

Inheritance - introduction

• Inheritance is a process of constructing or designing one class from


another
Classical Inheritance
• Represents a kind of relationship between two classes
• Example:

• Here class A is refered to as base class, parent class or super class


• Class B is referred to as derived class, child class or sub class
• Also referred to as “is-a” relationship
• Example:
• Dog is-a type of Animal
• Ford is-a type of Car
Classical Inherit Implementation
Containment Inheritance

• Also known as containership inheritance


• Example
class A
{
}
class B
{
private A field; //a is contained in B
}
• Here object A is contained in B
• The relationship is reffered to “has-a” relationship
• Example:
• Cas has-a radio
• City has-a road
Subclass definition

• Syntax:
class subclass-Name : baseClass-Name
{
variable declaration;
method declaration
}
Inheritance - example
Characteristics of inheritance

• A derived class extends its direct base class. It can add new members to
those it inherits. However, it cannot change or remove the definition of an
inherited member
• A derived class can hide an inherited member
• A derived class can override an inherited member
• An instance of a class contains a copy of all instance fields declared in
the class & its base class
• Constructors are not inherited
Class Visibility

• Public: Accessible within and outside the program assembly


• Internal (default): Accessible only within program assembly
• Private: Accessible only within the class
Class members visibility

• Public
• Private
• Protected
• Internal
• Protected internal
Class members visibility
Accessibility Constraints

• Constraints on the accessibility of members and classes when they are


used in process of inheritance:
• The direct base class of a derived class must be at least as
accessible as the derived class itself
• Accessibility domain of a member is never larger than that of the
class containing it
• The return type of a method must be as accessible as the method
itself
Subclass constructor example
Multilevel Inheritance
• Uses derived class as a parent

• Here is A as base class for B which in turn as base class for C


• The chain ABC is known as a inheritance path
• This process may be extended to any numbers of levels
Multilevel Inheritance example
Method Overriding

• In derived class we can create a method with same signature as in base


class.
• This concept is called as method overriding.
• This method can have same name, same arguments and same return
type as a method in base class
• When the method is called, the method defined in the subclass is invoked
and executed
• The method in base class should be specified as virtual.
• The method in base class should be specified with keyword override
Method overriding example
Abstract classes

• At times we can have one base class and a number of different derived
classes
• The top-most base class simply acts as a base for others & is not useful
on its own
• We might not want to create an objects of such classes
• This can be done by making the class as abstract.
Abstract methods

• Method declaration includes the modifier abstract


• It is implicity a virtual method and does not provide any implementation
• An abstract method does not have a method body
• Example:
public abstract void Draw(int x, int y);
• Characteristics:
• It cannot have implementation
• It can be declared only in abstract classes
• It cannot take either static or virtual modifiers
• An abstract definition is permitted to override a virtual method
Sealed classes

• Prevent a class from being further sub classes


• Such classes are called sealed classes
• Any attempt to inherit these classes will cause an error and compiler will
not allow it
• Standalone utility classes are created as sealed classes
Excersise
Create a new C # project with three classes plus another class to test the logic in your code.
The main classes of the program are the following classes:
• Person
• Student
• Professor
The Student and Teacher classes inherit from the Person class.The Student class will include a
public Study() method that will write I'm studying on the screen.The Person class must have
two public methods Greet() and SetAge(int age) that will assign the age of the person.The
Teacher class will include a public Explain() method that will write I'm explaining on the
screen.Also create a public method ShowAge() in the Student class that writes My age is: x
years old on the screen.You must create another test class called StudentProfessorTest with a
Main method to do the following:
Create a new Person and make him say hello
Create a new Student, set an age, say hello, and display her age on the screen.
Create a new Teacher, set an age, say hello and start the explanation.
Polymorphism

• Means “one name… many forms”


• Polimorpism can be achived in two ways
Operation Polymorphism

• Implemented using overloaded methods and operators


• Overloaded methods are selected for invoking by matching arguments,
in terms of number, type and order
• This information is known to compiler at compile time
• Also called as early binding, or static binding or static linking
• Also known as compile time polymorphism
• Early binding means an object is bound to its method call at compile
time
Operation Polymorphism - example
Inclusion Polymorphism

• Achieved through use of virtual functions


• Assume class A implements virtual method M. Classes B & C are derived
from A and override method M. When B is cast to A, a call to method M
from A is dispatched to B. Similarly when C is cast to A, a call to method M
from A is dispatched to C
• Also known as run-time polymorphism
• Since method is linked with a particular class much later after
compilation, this process is also called late binding
• Also known as dynamic binding as the selection of method is done
dynamically at run time
Inclusion Polymorphism example
Excersise

• Write a program using Virtual and Override keyword that does the
following tasks.
• A virtual function Engine() that has basic properties of engine like Power
of engine, RPM, no of Cylinder etc.
• This function should be overridden in child class according to function.
Interface

• C# does not support multiple inheritance


• Class cannot have more than one superclass
• C# provides an approach known as interface to support the concept of
multiple inheritance
• An interface is a class with some differences
• All members of an interface are implicitly public and abstract
• An interface cannot contain constant fields, constructors
• Its members cannot be declared static
Defining an interface

• General Form:
interface InterfaceName
{
member declaration
}
• Like classes, interfaces can also be extended.
• That is, an interface can be sub interfaced from other interfaces
• General Form:
interface name2 : name1
{
members of name2
}
• An interface can not extend classes
Interface example
Abstract classes and interfaces
• An abstract class can use interface in the base class list
• Here the interface metrhods are implemented as abstract methods
• Example:
interface A
{
void Method();
}
Abstract class B : A
{
public abstract void Method();
}
• Here class B not impelemnted the interface method: it simply redeclares as a public
abstract method
• It is the duty of the class that derivies from B to override and implement the method
Nested classes

• A class defined within another class is called nested. (Default - private)


class Container
{
class Nested
{
// Add code here.
}
}
• To create an instance of the nested class, use the name of the container
class followed by the dot and then followed by the name of the nested class:
• Container.Nested nestedInstance = new Container.Nested()
Anonymous types

• An anonymous class is a local class that does not have a name.


• An anonymous class allows an object to be created using an expression
that combines object creation with the declaration of the class.
• This avoids naming a class, at the cost of only ever being able to create
one instance of that anonymous class.
• An anonymous class is defined as part of a new expression and must be
a subclass or implement an interface
• The class body can define methods but cannot define any constructors.
• The restrictions imposed on local classes also apply
Anonymous type - example
Exceptions introduction

• The exception in .NET framework are classic implementation of the OOP


exception model
• Deliver powerfull mechanism for centralized handling of errors and
unusual events
• Substitute procedure-oriented approach in which each function returns
error code
• Simplify code construction and maintance
• Allow the problematic situations to be processed at multiple levels
Handling exceptions

• In c# the exceptions can be handled by the try-catch-finally construction


try
{
// Do some work that can raise an exception
}
catch(SomeException)
{
//Handle the caught exception
}
• Catch block can be used multiple times to process different exception types
Handling exceptions - Example
System.Exception class

• Exception in .NET are objects


• The System.Exception is base for all exceptions in .NET
• Contains information for the cause of the error or unusual situation
• Message – text description of the exception
• StractTrace – the snapshot of the stack at the moment of
exception throwing
• InnerException – exception caused the current exception
Exception properties

• The MessageMessage property gives brief description of problem


• StackTrace property is extremely useful when identifying the reason
caused the exception
• File names and line numbers are accessible only if the compilation was
in Debug mode
• When compiled in Release mode, the information in the property
StackTrace is quite different
Exception hierarchy

• Exceptions in .NET are organized in hierarchy


Handling exceptions

• When catching an exception of a particular class, all its inheritors are caught too
• Example:
try
{
// Do some work that raise an exception
}
catch(ArithmeticException)
{
// Handle the caught arithmetic exception
}
• Handles ArithmeticException and its successors DivideByZeroException and
OverlowException
Be Careful!
Handling all exceptions

• All exceptions thrown by .NET managed code inherit the System.Exception


exception
• Unmanagemnt code can throw other exceptions
• For handling all exceptions use the construction:
try
{
//Do some work that may raise an exception
}
catch
{
//handle the caught exception
}
Throwing exceptions

• Exceptions are thrown by throw keyword in C#


• When an exception is thrown
• The program executes stop
• The exception travel over the stack until a suitable catch block is
reached to handle it
• Unhandled exceptions display error message
Using throw keyword

• Throwing an exception with error message


throw new ArgumentException(“Invalid Argument!”);
• Exceptions can take message and cause
try
{
Int32.Parse(str);
}
catch(FormatException fe)
{
throw new ArgumentException(“Invalid number”, fe);
}
• Note: if the original exception is not passed the initial cause of the exception is
lost
Re-Throwing exceptions

• Caught exception can be re-thrown again:


try
{
Int32.Parse(str);
}
catch(FormatException fe)
{
Console.WriteLine(“Parse Failed”);
throw fe; // re-throw the caught exception
}
//another ver
Catch(FormatException fe)
{
throw; //re-throw the last caught exception
}
Throwing exceptions - example
Try-finally construction

• The construction:
try
{
//Do some work that cause the exception
}
finally
{
//this block will always execute
}
• Ensures execution of given block in all cases
• Used for execution of cleaning-up code, eg: releasing resources
try-finally example
Collections

• A collection is a set of similarly typed objects that are grouped


together.
• The principal benefit of collections is that they standardize the way
groups of objects are handled by your programs.
• Collections are data structures that holds data in different ways for
flexible operations . C# Collection classes are defined as part of the
System. Collections or System.Collections.Generic namespace.
• Most collection classes implement the same interfaces, and these
interfaces may be inherited to create new collection classes that fit
more specialized data storage needs.
Dictionary

Fast lookups are critical. The Dictionary type provides fast lookups
with keys to get values. With it we use keys and values of any type,
including ints and strings.
Dictionary - example
List

Arrays do not dynamically resize. The List type does. With List, you do not
need to manage the size on your own. This type is ideal for linear collections
not accessed by keys. It provides many methods and properties.
List - example
Queue

• Queue is a FIFO collection. It processes elements in a first-in, first-out


order. To restate, it handles the elements that it received longest ago first.
• Queue is a generic type with one type parameter
Queue - example
Stack

• The Stack class represents a last-in-first-out (LIFO) Stack of Objects.


Stack follows the push-pop operations. That is we can Push (insert) Items
into Stack and Pop (retrieve) it back . Stack is implemented as a circular
buffer. It follows the Last In First Out (LIFO) system. That is we can push the
items into a stack and get it in reverse order. Stack returns the last item
first. As elements are added to a Stack, the capacity is automatically
increased as required through reallocation.
Stack - example
Attributes

• Are use to associate information (metadata) with types and members,


e.g
• Documentation URL for a class
• XML persistence mapping
• Attributes allow you to decorate a code element
• Assembly, module, type, member, return value and parameter) with
additional information
Attribute - example
Attributes - continue

• Attributes are superior to the alternatives


• Modifying the source language
• Using external files, e.g., .IDL, .DEF
• Attributes are extensible
• Attributes allow to you add information not supported by C# itself
• Not limited to predefined information
• Built into the .NET Framework, so they work across all .NET languages
• Stored in assembly metadata
Predefined Attributes

•Browsable
Should a property or event be displayed in the property window
•Serializable
Allows a class or struct to be serialized
•Obsolete
Compiler will complain if target is used
Generic types

• Generics introduce to the .NET Framework the concept of type


parameters, which make it possible to design classes and methods that
defer the specification of one or more types until the class or method is
declared and instantiated by client code. For example, by using a generic
type parameter T you can write a single class that other client code can
use without incurring the cost or risk of runtime casts
• Generics (C# Programming Guide)

• Link
Writing Generic class

• class SomeName<T> {
// T can be used inside class as
// parameter type
// return type
// property type
}
• Naming convention: The type parameter is usuall call ‘T’
Default values

• Sometimes you need to get a default value for a generic type parameter
• Example: T find(int id)
• If there is no element with the specified id we want to return the default value

• Default values
• Null: References types, like String, etc.
• O: int, etc.
• False: bool
• Default value table http://msdn.microsoft.com/en-us/library/83fhsxwc.aspx
• Syntax
• default(T)
• T find(int id) { …. return default(T); }
Generic constraints

• In a generic class, all you can do to a variable of the type parameter, are the
operations defined in the class Object
• That is not much! ToString(), Equals(), etc.
• If you want more you must constrain the type parameter
• Generics constraints guarantees that the type has certain operations
• Example: GenericConstraints
• Syntax
• Class SomeName<T> where T : constraint { … }
• Class SomeName<T> : ISomeInterface where T : constraint { … }
• Different types of constraints
• http://msdn.microsoft.com/en-us/library/d5x73970.aspx
Generic Methods

• Methods, as well as classes + interfaces, can be generic.


• Generic methods are usually static
• Example String.Join(…) method
• Public static string Join<T>(string separator, IEnumerable<T> values)
• Example Enumerable.Where(…) method
Concurrency Introduction

• Concurrency is a key aspect of good software


• For decades concurrency was possible but difficult
• Concurrency software was difficult to write, to debug and maintain
• As a result many developers chose the easier path and avoided
concurrency
• However, with the libraries and language features available for modern
.NET programs, concurrency is much easier
• Previously, concurrency programming was the domain of experts, these
days every developer can (and should) empbracy concurrency
Definitions

• Concurrency
• Doing more than one thing at a time
• Multithreading
• A form of concurrency that uses multiple threads of execution
• Parallel Processing
• Doing lots of work by dividing it up among multiple threads that run
concurrenty
• Asynchronous Programming
• A form of concurrency that uses futures or callbacks to avoid
unncecesary threads
Concurrency: Benefits

• End-user applications use concurrency to respond to user input while


writing to a database
• Server applications use concurrency to respond to a second request
while finishing the first request
• You need concurrency any time you need an application to do one thing
while it’s working on something else
• Almost every software application in the world can benefit from
concurrency
Multithreading

• Multithreading literally refers to using multiple threads

• Multithreading is one form of concurrency, but certainly not the only one

• A thread is an independent executor

• Each process has multiple threads in it, and each of those threads can be
doing different things simultaneously
• Each thread has its own independent stack but shares the same memory
with all the other threads in a process
Multithreading

• In some applications, there is one thread that is special


• User interface applications have a single UI thread; Console applications
have a single main thread
• In fact, direct use of the low-level threading types has almost no purpose
in a modern application
• Higher-level abstractions are more powerful and more efficient than old-
school multithreading
Multithreading

• But don’t get the idea that multithreading is dead


• Multithreading lives on in the thread pool, a useful place to queue work that
automatically adjusts itself according to demand
• Every .NET application has a thread pool
• The thread pool maintains a number of worker threads that are waiting to
execute whatever work you have for them to do
• The thread pool is responsible for determining how many threads are in the
thread pool at any time
• There are dozens of configuration settings you can play with to modify this
behavior, but I recommend that you leave it alone; the thread pool has been
carefully tuned to cover the vast majority of real-world scenarios
• There is almost no need to ever create a new thread yourself
Parallel programming

• Parallel programming should be used any time you have a fair amount of
computation work that can be split up into independent chunks of work
• Parallel programming increases the CPU usage temporarily to improve
throughput; this is desirable on client systems where CPUs are often idle but is
usually not appropriate for server systems
• Parallel processing (or parallel programming) uses multithreading to maximize
the use of multiple processors
• Modern CPUs have multiple cores, and if there’s a lot of work to do, then it makes
no sense to just make one core do all the work while the others sit idle
• Parallel processing will split up the work among multiple threads, which can each
run independently on a different core
• Parallel processing is one type of multithreading, and multithreading is one type
of concurrency
Asynchronous Programming

• There’s another type of concurrency that is important in modern applications but


is not (currently) familiar to many developers: asynchronous programming
• A future, a type that represents some operation that will complete in the future
• Future types in .NET are Task and Task<TResult>. Older asynchronous APIs use
callbacks or events instead of futures
• Asynchronous programming is centered around the idea of an asynchronous
operation: some operation that is started that will complete some time later
• While the operation is in progress, it does not block the original thread; the thread
that starts the operation is free to do other work
• When the operation completes, it notifies its future or invokes its completion
callback event to let the application know the operation is finished
Asynchronous Programming

• Asynchronous programming is a powerful form of concurrency, but until


recently, it required extremely complex code
• The async and await support in VS2012 make asynchronous
programming almost as easy as synchronous (nonconcurrent)
programming
• Modern asynchronous .NET applications use two keywords:
• async
• await
Asynchronous Programming

• The async keyword is added to a method declaration, and its primary


purpose is to enable the await keyword within that method
• An async method should return Task<T> if it returns a value, or Task if it
does not return a value
• These task types represent futures; they notify the calling code when the
async method completes
Example
Multithreading: Implementation
principles
• To perform any multiple task simultaneously means Threading
• For example executing Microsoft PPTX and Excel simultaneously in a
desktop, laptop or any device is known as Threading
• Work or a code task is always been executed in a two ways i.e.
Synchronous or Asynchronous way
• Synchronous way means where work multiple jobs are executed one
after the other
• Synchronous way means where work multiple jobs are executed one
after the other
Multithreading: Implementation
principles
Multithreading: Implementation
principles
Asynchronous means multiple work has been executed simultaneously like
doing multitask at a same time
Multithreading: Implementation
principles
• For creating threading application there some important methods
which used regularly for implementing threading
• Thread Join
• Thread Sleep
• Thread Abort
Types of thread

• Foreground
• Foreground threads are those threads which keeps running until it
finishes his work even if the Main method thread quits its process
• Lifespan of foreground threads does not depends on main thread
• Background
• Background thread is just opposite of foreground thread here
background thread quits its job when main thread quits
• Here lifespan of background threads depends on main thread
Multithreading

• To control abnormal behaviour of an object in a multi-threaded


environment is called as Thread Safety
• In order to make a thread as thread safe there are some thread
synchronization techniques like:
• Monitor/Lock
• Mutex
• Semaphore
• SemaphoreSlim
Example
Thread life cycle
Thread pool
Thread Pool lifecycle
Thank you!

You might also like