Full Transcript

1.1 Background Introduction C# is a modern, high-level, general-purpose, object-oriented programming language. Principal language of the.NET framework. A framework is a platform for developing software applications. Includes predefined classes and functions that can be used to process...

1.1 Background Introduction C# is a modern, high-level, general-purpose, object-oriented programming language. Principal language of the.NET framework. A framework is a platform for developing software applications. Includes predefined classes and functions that can be used to process input, input, manage hardware devices, and interact with system software C# is used to create applications for stand alone, web based and mobile APIs. It is a one single programming language for multiple device range. 3 www.belgiumcampus.ac.za 1.2 Key Terms In this slide, will discuss some of the key concepts and their practical implementation in C#. These include: Classes Objects Methods 4 www.belgiumcampus.ac.za Classes and Objects Example#1: Consider an ATM. Think of it as a class. It’s a machine which is pretty much useless until you insert your card [an object]. After you insert your card, the machine gets information, from your card, about you and your bank account and the balance in it [information about the object]. 5 www.belgiumcampus.ac.za Example#1: Consider an ATM… Once you use a class (ATM) and its object (card), now you can perform operations on the object, like withdrawal of money or checking you balance or getting statement of your account. These operations will be methods belonging to that class (ATM) [but you cannot use them until you create an object out of it.] Methods (operations) belong to a class (ATM), and we use objects (card) access to those methods. 6 www.belgiumcampus.ac.za Defining a Class A class is a user-defined blueprint or prototype from which objects are created. 7 www.belgiumcampus.ac.za Example#2: Consider Automobiles An automobile is a means of transportation that usually has wheels and an engine. Automobile - example of class Car, Bus, Bike (e.gs of automobiles) - possible sub-classes of automobile class Polo, i20 - Objects of Car class Quantum, Minibus – Objects of Bus class Scooter, Cruiser – Objects of Bike class 8 www.belgiumcampus.ac.za Defining Objects An object is an instance of a created class. Each object will have a state and some behavior. An object's state is the data or information it contains. Behavior in an object is often represented by methods. 9 www.belgiumcampus.ac.za Defining Behavior in a Class A Person with name = Alfred, height = 1,72m, weight = 95kgs, gender = male, and age = 43 can walk, run, jump, speak and sleep. Person is the class, which can define ANYONE else (say Nicole), with different attributes, but has same behaviors 10 www.belgiumcampus.ac.za Classes and Objects 11 www.belgiumcampus.ac.za Creating a Class Classes are declared by using the keyword class followed by the class name and a set of class members surrounded by curly braces { }. A Class is made up of the following:  Access modifiers - specify access rules for the members and the class itself. [private, public or internal]  class keyword and class name (Example)  Class Members - specifies properties, data fields and methods (functions) that operate on the data in the variables. 12 www.belgiumcampus.ac.za Class Members Classes in C# can have members: Data fields, methods, properties, indexers, events, operators, constructors, destructors, … Members can have access modifiers public, private, … Members can be static (common) or specific for a given object 13 www.belgiumcampus.ac.za Fields and Methods Fields: A field (variable), in C#, is a member of a class or an object of any type that represents a memory location for storing a value. E.g int myAge; Methods: A method is a group of statements that together perform a task. Every C# program has at least one class with a method named Main. To use a method, you need to: Define the method Call/Invoke the method 14 www.belgiumcampus.ac.za Creating a Class in Visual Studio 2017/2019/2022 Example: Namespaces (collection of predefined classes/elements) You create your own Namespace (which you define) You can create your own class, with your own methods Default class which runs your program, with Main method 15 www.belgiumcampus.ac.za Basic syntax for class declaration In C#, individual classes and class members can be prefixed with access modifiers. By default, if you declare a member variable (or anything else) in a class but do not specify its access level, the member is considered private and cannot be accessed from outside, i.e. by a non-member of that class. Therefore, to make a member accessible by other classes, you must declare it as public. You can use a mix of public and private members in a class and there is no rule on which access level should be listed first or last. 16 www.belgiumcampus.ac.za Creating a class object We use the new operator when creating an instance of the class (object). Custom class House Object beachHouse, of type House 17 www.belgiumcampus.ac.za Class and Object Example: Question: Create a custom class with member field myAge, and a method printMyAge() that will display the myAge field. Create an object of the class, that will invoke the printMyAge() method, in main method. 18 www.belgiumcampus.ac.za Class and Object Example: Solution: 19 www.belgiumcampus.ac.za Class and Object Example: Solution: 20 www.belgiumcampus.ac.za Exercise 1. Create a Box class with length and width field members, which will utilize a calculateArea() method member to print the area of the box. Use literal values for your fields. 2. Using classes, objects, fields, methods and console input and output, create a console App that will run as follows: 21 www.belgiumcampus.ac.za Learning objectives In this presentation we will be looking at what a class definition consists of: Understanding fields and Initialization Defining Access Modifiers Constructors Properties 2 www.belgiumcampus.ac.za Background We have seen that C# classes can have members (variables/fields + methods). These are the building blocks of a class, and we need to understand how properties and access modifiers will work together with them. 3 www.belgiumcampus.ac.za Declaring a Field To declare a field, you must specify at least a field type and a field name. Multiple fields with the same type can be put on a single line in a comma- separated manner, just like you can do for variables within a code block. 4 www.belgiumcampus.ac.za Access Modifiers An access modifier describes access to a class and its member fields. They describe the scope of accessibility of an Object and its members. We have 4 Main Access Modifiers we use in C#: 5 www.belgiumcampus.ac.za Access Modifiers… By default, all fields are private. You have to manually declare them either public, protected or internal for them to change. How to utilize Access Modifiers: https://code-maze.com/csharp-basics-access-modifiers/ 6 www.belgiumcampus.ac.za Example: Lets create a class called Dog, with the following public fields: Name, age, height and weight. Lets also create a method called currentStatus() to display the following: 7 www.belgiumcampus.ac.za Explanation We can create a general representation/template of a dog (a class called Dog). We have variables inside the class which holds data for this class. These are called fields. Together with methods, fields help create our dog representation to be what we know a dog to be made up of and what they do. Fields represent the data we want for a dog. Methods are the processes where we use that data and include the behaviors of our dog. 8 www.belgiumcampus.ac.za Declaring vs. Initializing Fields Field declaration is the process of creating a our field/variable, without passing it a value. Example: Field initialization is the process of assignment our fields/variables some values. In the Dog class, we could assign values to name, age, height and weight fields manually as: 9 www.belgiumcampus.ac.za We create the Dog class as following: 10 www.belgiumcampus.ac.za Problem with Initializing fields in class!!! This is ok, but the problem comes when we want to display data of a different dog. Since the values of the fields have been manually entered, when we run our program, we wont be able to change them. To get around this problem, its best to use OOP principles, by utilizing objects. “Instead of initializing fields of a class when we create the class, we can now utilize objects to initialize the fields”…Jay-Z Zuma (2025) 11 www.belgiumcampus.ac.za Initialization via objects This is done in the Main() method. Lets create an object obj as follows: 12 www.belgiumcampus.ac.za Initialization via objects Remember, an object is an instance of a class. When we initialize using different objects, we create different instances of different dogs. We can therefore, create a second instance of a dog, using object obj1 as follows: 13 www.belgiumcampus.ac.za Classes & their objects At the end, we are using the SAME class, Dog, to create two or more instances (objects) of dogs, “sparky” and “rin tin tin” 14 www.belgiumcampus.ac.za Making things simple: Constructors Lets look closely at our object initialization: But surely there must be a better way of initializing all our fields, and not in a line by like way: Constructors to the rescue. 15 www.belgiumcampus.ac.za Constructors It is not uncommon for a class to have dozens of fields to contend with. Clearly, it would be undesirable to create 20-initialization statements so as to set 20 fields of data in a class, via its object. C# supports the use of class constructors. A constructor is a special method that is used to initialize fields of a class, when we invoke its object using the new keyword, in a simple manner. A constructor allows the state of an object to be established at the time of creation. There are two types: Default and the Custom constructor 16 www.belgiumcampus.ac.za Default Constructor Whenever you create a class, C# will create a default constructor inside that class for you. Every C# class is provided with a free default constructor that you may redefine if need be. By definition, a default constructor never takes arguments. Beyond allocating the new object into memory, the default constructor ensures that all field data is set to an appropriate default value. 17 www.belgiumcampus.ac.za Custom Constructors We create our custom constructor in our Dog class look like this: 18 www.belgiumcampus.ac.za Custom Constructors… In our Main() method, we create an object of Dog, which will utilize the Dog Constructor: We can now initialize all fields in the class, via our object, in one statement, instead of 4 initialization statements, line by line. 19 www.belgiumcampus.ac.za This keyword The this keyword is a predefined variable available in non-static function members Used to access data and function members unambiguously public class Person { private string name; public Person(string name) { name is a parameter this.name = name; } } name is our private file, declare above 20 www.belgiumcampus.ac.za Destructors [Finalizers] Destructors are used to clean up any resources that your class was holding on to during its life time. As opposed to a constructor, a destructor is called when a program has finished using an object. A destructor does the cleaning behind the scenes. 21 www.belgiumcampus.ac.za C# Properties So far we have been dealing with public fields in our classes. This is not a safe way of working with classes (data fields are directly accessible outside the class). We need to utilize private/protected fields by using a property. A property is a member of a class that provides a flexible way for a class to expose its private fields. 22 www.belgiumcampus.ac.za GET and SET Accessors Internally, C# properties are special methods called accessors. A C# property have two accessors: a) get accessor property b) set accessor property A get accessor returns a property value, and a set accessor assigns a new value. The value keyword represents the “value” of a property 23 www.belgiumcampus.ac.za Creating C# Properties In C#, properties are nothing but a natural extension of data fields. 24 www.belgiumcampus.ac.za Accessing C# Properties We can then utilize objects in the Main() method to assign values to the private field: 25 www.belgiumcampus.ac.za Exercise 1: public class Dog { private string name; private string breed; public Dog() //Constructor { name = "Fido"; breed = "Mongrel"; } } Task is as follows, using the class above: Create a property for Dog class Create a method in Dog class for display. Create 3 dog instances in Main Put all dogs in an array Iterate through the array elements and ask each dog to bark; display: 26 www.belgiumcampus.ac.za Learning Objectives Four pillars of OOP 2 www.belgiumcampus.ac.za Object Oriented Programming 3 www.belgiumcampus.ac.za Overview Let us try to understand a little about all these, through a simple example. Human Beings are living forms, broadly categorized into two types, Male and Female, right? It’s true. Every Human being (Male or Female) has two legs, two hands, two eyes, one nose, one heart etc. There are body parts that are common for Male and Female, but then there are some specific body parts, present in a Male which are not present in a Female, and some body parts present in Female but not in Males. All Human Beings walk, eat, see, talk, hear etc. Now again, both Male and Female, performs some common functions, but there are some actions applicable to one, which is not valid for the other. For example : a Female can give birth, while a Male cannot, so this is only for the Female. Human Anatomy is interesting, isn't it? But let's see how all this is related to C# and OOP. Here we will try to explain all the OOP concepts through this example and later we will have the technical definitions for all this. 4 www.belgiumcampus.ac.za Encapsulation Restricts access to some of an object’s components Private data members Data members only assessed through getter & setter methods. Advantages Private data members Data members only assessed through getter and setter methods 5 www.belgiumcampus.ac.za Example of encapsulation class MyClass class Program { { private string message; static void Main() public string Message { { // create instance of MyClass get MyClass greetings = new MyClass(); { return message; } greetings.Message = "Hello World!"; set { string answer = greetings.Message; message = value; } } Console.WriteLine("{0}", answer); } Console.ReadLine(); } } 6 www.belgiumcampus.ac.za Access Modifiers In C#, private is the default accessibility Accessibilities options public – Accessible to all private – Accessible to containing class protected – Accessible to containing or derived classes internal – Accessible to code in same assembly protected internal – means protected or internal Classes can be marked as public or internal By default they are private Accessible only to code in the same source module 7 www.belgiumcampus.ac.za Access Modifier Summary 8 www.belgiumcampus.ac.za Inheritance Inheritance enables new classes to receive—or inherit—the properties and methods of existing classes. 9 www.belgiumcampus.ac.za Inheritance By using Inheritance methodology we can create a new class by using existing class code. In Inheritance main existing class is called as generalized class, base class, super class or parent class. The new class created from existing class is called as specialized class, sub class, child class or derived class. We normally talk in terms of base class and derived class. The Child class extends Base Classes. 10 www.belgiumcampus.ac.za Polymorphism 11 www.belgiumcampus.ac.za Polymorphism Real Life Example 12 www.belgiumcampus.ac.za Polymorphism and Virtual Functions Use the virtual keyword to make a method virtual In derived class, override method is marked with the override keyword Example ToString() method in Object class Example derived class overriding ToString() class SomeClass:Object{ public override String ToString(){ return “Some String Representing State”; } } 13 www.belgiumcampus.ac.za Abstraction 14 www.belgiumcampus.ac.za Abstraction Example 15 www.belgiumcampus.ac.za Learning Objectives Understanding the Four pillars of OOP Inheritance in Classes without Constructor Inheritance And Constructors Exercise 2 www.belgiumcampus.ac.za The four Pillars of OOP 3 www.belgiumcampus.ac.za Inheritance Explanation Inheritance involves a base class and a derived class. The derived class inherits from the base class and also can override inherited members as well as add new members to extend the base class. A base type represents the generalization, whereas a derived type represents a specification of an instance. When inheriting from a class, the derived class inherits the members including the code of the base class. 4 www.belgiumcampus.ac.za Inheritance Example In Main() method: 5 www.belgiumcampus.ac.za Inheritance Example [Without Constructor] We can have a parent class Person, whose attributes are inherited by a derived class Student 6 www.belgiumcampus.ac.za Inheritance And Constructors Inheritance enables new classes to receive—or inherit—the properties and methods of existing classes. It is the mechanism by which one class is allowed to inherit the features (fields and methods) of another class. By doing this, we are reusing the fields and methods of the existing class. 7 www.belgiumcampus.ac.za Inheritance And Constructors Say we have a base class called Animal (with fields – name, age and method called Details) 8 www.belgiumcampus.ac.za Now we create sub classes, starting with Dog: 9 www.belgiumcampus.ac.za Protected Access Modifier public means that your object's method can be called from anywhere, or that the instance variable that you declare public can be accessed from anywhere, whether outside or inside the class itself. private is the opposite to public: private variables and methods can only be accessed from within the class. protected is useful when you want your class and all derived (child) classes to be able to access the method or variable, but you don't want it to be public. 10 www.belgiumcampus.ac.za Now we create sub class Bird: 11 www.belgiumcampus.ac.za In Main() method: There are many ways to instantiate object of parent or child classes. First way: We can utilize Animal base class to create an Animal object. This will utilize the base class constructor ONLY. Second way: we can do it using 2 methods We can utilize Animal base class to create a Dog object. This will utilize the derived class constructor. We can utilize Dog derived class to create a Dog object. This will utilize the derived class constructor. 12 www.belgiumcampus.ac.za In Main() method: For bird class: We can utilize Animal base class to create a Bird object. This will utilize the derived class constructor. We can utilize Bird derived class to create a Bird object. This will also utilize the derived class constructor. 13 www.belgiumcampus.ac.za Why use Inheritance? All object-oriented programming languages make use of inheritance for the same reasons: a) To organize the objects that programs use. b) To make new objects easier to understand based on your knowledge of their inherited traits. c) The classes you create in object-oriented programming languages can inherit data and methods from existing classes. d) When you create a class by making it inherit from another class, you are provided with data fields and methods automatically; you can reuse fields and methods that are already written and tested. 14 www.belgiumcampus.ac.za Purpose of Inheritance Reuse: means reuse of class definition without requiring major code changes. Extend: extending the parent class definition either by augmenting or overriding behavior defined there. Modification: You can also add new data members and member functions to the derived class. You can modify the implementation of existing member functions or data by overriding base class member methods or data in the newly derived class. NOTE : All members of a class except private members, are directly accessible 15 www.belgiumcampus.ac.za Types of Inheritance Single Inheritance Multiple Inheritance Hierarchical Inheritance Multilevel Inheritance Hybrid Inheritance 16 www.belgiumcampus.ac.za Single Inheritance In this type of inheritance one derived class inherits from only one base class. It is the most simplest form of Inheritance. 17 www.belgiumcampus.ac.za Multiple Inheritance In this type of inheritance a single derived class may inherit from two or more base classes. Due to the complexity of multiple inheritance, it has not been supported in C# or in DOT.NET DOT.NET C# does supports multiple interface inheritance. 18 www.belgiumcampus.ac.za Hierarchical Inheritance In this type of inheritance, multiple derived classes inherits from a single base class. 19 www.belgiumcampus.ac.za Multilevel Inheritance In this type of inheritance the derived class inherits from a class, which in turn inherits from some other class. The Super class for one, is sub class for the other. 20 www.belgiumcampus.ac.za Hybrid Inheritance Hybrid Inheritance is a combination of Hierarchical and Multilevel Inheritance. 21 www.belgiumcampus.ac.za Interactive Session Exercise Show inheritance using the following class diagram: 22 www.belgiumcampus.ac.za Learning Objectives Purpose of abstraction Example of abstraction Basic abstract class syntax Abstract classes and methods Rules to abstract classes 2 www.belgiumcampus.ac.za Background Humans manage complexity through abstraction. It is a form of complex-implementation hiding. For example, people do not think of a car as a set of tens of thousands of individual parts. They think of it as a well-defined object with its own unique behavior. This abstraction allows ordinary people to drive the car without being overwhelmed by the complexity of the parts that form the car. They can ignore the details of how the engine, transmission, and braking systems work. Instead, they are free to utilize the object as a whole. The car is a perfect example of abstraction utilization. 3 www.belgiumcampus.ac.za Background As a programmer, you must aim to hide all but the relevant data about an object, in order to reduce complexity and increase efficiency. Abstraction is simply a case of hiding details about how a thing works. So if you are writing a program, and say you want to produce console output, you might need to use a third-party library, like Console.WriteLine(), which is a system defined method, designed by someone else. Remember, WriteLine() method is under the using system namespace/class. As long as you know how and when to use the library (Console.WriteLine()) in your code, all you do is to simply call the method to achieve what you want your program to do (to print). You do not need to know how that library works. 4 www.belgiumcampus.ac.za Example of Abstraction Abstraction is the process of hiding certain details and showing only essential information to the user. Abstraction can be achieved with either abstract classes or interfaces. 5 www.belgiumcampus.ac.za Basic Abstract Class Syntax Syntax: Abstract methods are methods without implementation Non-Abstract methods are methods which has some implementation 6 www.belgiumcampus.ac.za Example of Abstraction Say we have an abstract class Vehicle: You can either declare is abstract or virtual 7 www.belgiumcampus.ac.za Example of Abstraction We can then create custom derived classes, that will inherit from vehicle: Truck class: 8 www.belgiumcampus.ac.za Example of Abstraction We can then create custom derived classes, that will inherit from vehicle: Car class: 9 www.belgiumcampus.ac.za Example of Abstraction We can then create custom derived classes, that will inherit from vehicle: Bike class: 10 www.belgiumcampus.ac.za Example of Abstraction In our Main Method: 11 www.belgiumcampus.ac.za Abstract Classes Summary An Abstract class is a restricted class that defines some fields and methods (abstract methods), and those fields do not have an implementation. When this Abstract class gets inherited by derived classes, it enforces the derived classes to provide all implementation logic for abstract methods or properties. An abstract class is designed to be inherited by subclasses that either implement or override its methods. In other words, abstract classes are either partially implemented or not implemented at all. The methods in an abstract class can either be abstract and concrete methods. 12 www.belgiumcampus.ac.za Rules for using Abstract classes Abstract class in c# must be defined using "abstract" keyword. An abstract class may contain abstract methods and accessors (properties). Non abstract methods in an abstract class should provide actual implementation. Abstract classes cannot be instantiated. An Abstract method must be implemented in the derived class using the override keyword. After overriding the abstract method in the derived class, we can derive this class in another class and again we can override the same abstract method with it. An abstract method cannot be private. The access modifier of the abstract method should be same in both the abstract class and its derived class. www.belgiumcampus.ac.za Interactive Session Exercise 1 Develop a console application for a bank, which has two classes savingsAccount and checkAccount. The different accounts should inherit from a bankAccount Class that will define the different fields, and methods that are going to be used. You are also required to include a menu using methods, that will be used to allow the user to make a choice of which account to access. Use decision logic as well. Use given class diagram below as a guide to building your application. 14 www.belgiumcampus.ac.za Class Diagram Interactive Session 15 www.belgiumcampus.ac.za The console application should output the following if a user chooses savings Interactive Session account 16 www.belgiumcampus.ac.za If the user chooses Check account, the following output is displayed: Use 4000 as back balance amount Use 300 as debit order amount 17 www.belgiumcampus.ac.za Learning Objectives Understand and apply Encapsulation 2 www.belgiumcampus.ac.za Encapsulation What is encapsulation? Encapsulation is the process of hiding irrelevant data from the user. It is used to hide its members from outside class or interface. Restricts access to some of an object’s components Private data members Data members only assessed through getter & setter methods. Advantages Private data members Data members only assessed through getter and setter methods 3 www.belgiumcampus.ac.za Example of encapsulation class MyClass class Program { { private string message; static void Main() public string Message { { // create instance of MyClass get MyClass greetings = new MyClass(); { return message; } greetings.Message = "Hello World!"; set { string answer = greetings.Message; message = value; } } Console.WriteLine("{0}", answer); } Console.ReadLine(); } } 4 www.belgiumcampus.ac.za Access Modifiers What is Access modifiers in C#? Access modifiers defines the scope of a class member. In C#, private is the default accessibility Accessibilities options public – Accessible to all private – Accessible to containing class protected – Accessible to containing or derived classes internal – Accessible to code in same assembly protected internal – means protected or internal Classes can be marked as public or internal By default they are private Accessible only to code in the same source module 5 www.belgiumcampus.ac.za Public Modifier The public keyword is a member access modifier. Public members are accessible anywhere in program or application. or The scope of the accessibility is inside class as well as outside. There is no restriction to access public access modifiers. We can declare public access modifier to a class, methods, property, structure, interfaces. 6 www.belgiumcampus.ac.za Private Modifier The private keyword is a member access modifier. Private members are accessible only within the body or scope of the class or the struct in which they are declared. We can declare private access modifier to a class, method, property, structure, interfaces. However if we do not specify any access modifier to a class, method, property, structure it will be assumed as private member only. 7 www.belgiumcampus.ac.za Protected Modifier The protected keyword is a member access modifier. The type or member can be accessed only by code in the same class or struct, or in a class that is derived(child class) from that class. We can declare protected access modifier to a class, method, property, structure, interfaces. 8 www.belgiumcampus.ac.za Internal Modifier The internal keyword is a member access modifier. Internal members are accessible within the same namespace scope in which it is declared or it is accessible in same assembly or same project. We can declare internal access modifier to a class, method, property, structure, interfaces. 9 www.belgiumcampus.ac.za Protected Internal Modifier The protected internal keyword is a member access modifier. The type or member can be accessed by any code in the assembly in which it is declared, or from within a derived class in another assembly. We can declare protected internal access modifier to a class, method, property, structure, interfaces. 10 www.belgiumcampus.ac.za Access Modifier Summary 11 www.belgiumcampus.ac.za Accessibility Levels Only one access modifier is allowed for a member or type, except when you use the protected internal combination. Access modifiers are not allowed on namespaces. Namespaces have no access restrictions. Depending on the context in which a member declaration occurs, only certain declared accessibilities are permitted. If no access modifier is specified in a member declaration, a default accessibility is used. Top-level types, which are not nested in other types, can only have internal or public accessibility. The default accessibility for these types is internal. 12 www.belgiumcampus.ac.za Default Access A default access level is used if no access modifier is specified in a member declaration. The following list defines the default access modifier for certain C# types: 13 www.belgiumcampus.ac.za Accessors The accessor of a property contains the executable statements associated with getting (reading or computing) or setting (writing) the property. The get method used for retrieving value from private field whereas set method used for storing value in private variables. The accessor declarations can contain a get accessor, a set accessor, or both. Syntax: set { accessor-body } get { accessor-body } 14 www.belgiumcampus.ac.za Get Accessors Get:The get { } implementation must include a return statement. It can access any member on the class. The get accessor can either be used to return the field value or to compute it and return it. A property with a get accessor only is called a read-only property. You cannot assign a value to a read-only property. Example: private string name; // the name field public string Name // the Name property { get { return name; //return the field value //or return name != null ? name : "NA";// compute it and return it } } 15 www.belgiumcampus.ac.za Get Accessors Set:The set { } implementation receives the implicit argument "value." This is the value to which the property is assigned. A property with a set accessor only is called a write-only property. You cannot reference a write-only property except as a target of an assignment. Example: public string Name //the Name property { get { return name; } set { name = value;} } 16 www.belgiumcampus.ac.za Learning Objectives Defining Interfaces Declaring Interfaces Implementing an interface Built-in interfaces Difference between abstract class and interface 2 www.belgiumcampus.ac.za Interface Concept An interface is like an abstract class which defines properties and methods that its sub-classes should have, and lets the sub-classes define the logic (implementation) of the inherited properties and methods. Abstract classes let you define some behaviours; they may force your subclasses to provide others. Interfaces are a collection of abstract methods (a method without body - no implementation) – all of them do not define any behaviours. 3 www.belgiumcampus.ac.za Declaring Interfaces Interfaces are declared using the interface keyword. It is similar to a class declaration. Interface members are public by default. Example of an interface declaration: A common naming convention is to prefix all interface names with a capital "I" 4 www.belgiumcampus.ac.za Rules for Interfaces A class that implements an interface supplies the implementation for its members. Interface methods do not have a body - the body is provided by the "implementing" class Like abstract classes, interfaces cannot be used to create objects. It is not possible to create any object of the interface in the Program class. On implementation of an interface, you must override all of its methods Interfaces can contain properties and methods, but not fields/variables Interface members are by default abstract and public An interface cannot contain a constructor (as it cannot be used to create objects) A class can always implement multiple interfaces (multiple-inheritance) 5 Interfaces may also inherit other interfaces. www.belgiumcampus.ac.za Implementing an interface An interface is implemented by a class or extended by another interface in the same way you derive a class from another class using the : notation. Example: 6 www.belgiumcampus.ac.za Interface Example Lets create an interface IAnimal: Lets create a class Cow, to implement the interface: 7 www.belgiumcampus.ac.za Multiple Interfaces: Example We create another interface: To implement multiple interfaces, separate them with a comma: 8 www.belgiumcampus.ac.za Interface Example We can now create an object of the Cow class, which invokes the method implemented on Cow: 9 www.belgiumcampus.ac.za Multiple Interfaces: Example In Main() 10 www.belgiumcampus.ac.za Built-in Interfaces In your applications, most of the interfaces you use will be built into the.NET Framework itself. The Framework is implemented with extensive interface use. We show some core ones in the.NET Framework. a) IEnumerable: The IEnumerable interface is used with many collections and also with LINQ. b) IList: The IList interface is a generic interface that is implemented by arrays and the List type. c) IDictionary: The IDictionary interface describes a lookup or dictionary collection. It has lookup methods, TryGetValue. d) IComparable: The IComparable interface describes how a type is sorted against other instances of the use of the CompareTo() method. 11 www.belgiumcampus.ac.za Difference Between abstract class and Interface 12 www.belgiumcampus.ac.za Learning Objectives Defining Polymorphism Examples of polymorphism Types of polymorphism Method Overloading Method overriding 2 www.belgiumcampus.ac.za Polymorphism What is Polymorphism? One name with multiple functionality. Polymorphism is in short, the ability to create members of the same name, but they may behave differently. The members could be inherited from the same parent class, but then we offer different implementation of the members, in the child classes. Polymorphism also referred to as having one name with many forms or having one name with multiple functionalities. 3 www.belgiumcampus.ac.za An Example of Polymorphism As an example, assume there is a base class named Animals from which the subclasses Horse, Fish and Bird are derived. Also assume that the Animals class has a function named Move, which is inherited by all subclasses mentioned. 4 www.belgiumcampus.ac.za Polymorphism Explained With polymorphism, each subclass may have its own way of implementing the function. So, when the move () function is called in an object of the Horse class, the function might respond by displaying trotting on the screen. When the move () function is called in an object of the Fish class, it will display it as swimming. In the case of the object for the Bird class, the move () function will display it as flying. 5 www.belgiumcampus.ac.za Types of Polymorphism There are two different types of polymorphism in OOP: Static Polymorphism - called as Compile time polymorphism (Early binding or Overloading) Dynamic Polymorphism - called as Runtime polymorphism, (Late binding or Overriding.) 6 www.belgiumcampus.ac.za Visualised 7 www.belgiumcampus.ac.za Static Polymorphism In Static polymorphism methods are overloaded with same name but having different signatures. This is known as method overloading. Two techniques to implement static polymorphism are: 1. Function overloading 2. Operator overloading 8 www.belgiumcampus.ac.za Function Overloading Signature will be different if:- 1. Number of parameters in the methods are different. EX:- show(int x), show(int x, int y), Here both have the same method name but the number of parameters are different. 2. Data types of parameters are different. EX:- display(int x, int y), display(int x, float y) Here both methods have the same name, but their parameter data types are different. 3. Sequence of data type of parameters are different. EX:- Display(int x, string y, float z), Display(int x, float y ,string z). Here both methods have the same name, but sequence of data type parameters are different. 9 www.belgiumcampus.ac.za Overloading Example Creating 2 Add () methods: 10 www.belgiumcampus.ac.za Overloading Example Now, in the Main() method: 11 www.belgiumcampus.ac.za Dynamic Polymorphism Dynamic polymorphism is also called Run Time polymorphism. In this type of polymorphism methods that have the same name, same signature but different in the implementation. In Dynamic polymorphism methods are overridden so it also called method overriding. During run time, method overriding can be achieved by using inheritance principle and using "virtual" and "override" keywords. 12 www.belgiumcampus.ac.za Dynamic Polymorphism Example 13 www.belgiumcampus.ac.za Polymorphism Syntax with Example 14 www.belgiumcampus.ac.za Method Overriding Creating a method in derived class with same signature as a method in base class is called method overriding. Method overriding is possible only in derived classes, not within the is declared. To allow the derived class to override a method of the base class, C# provides two options, virtual methods and abstract methods. 1. Virtual and Overridden Methods 2. Abstract and Overridden methods The virtual keyword is used to modify a method declared in the base class and allow it to be overridden in the derived class. The override keyword is used to extend or modify a virtual/abstract method, property, indexer, or event of base class into derived class. 15 www.belgiumcampus.ac.za Overriding Example We create one parent class and one child class: 16 www.belgiumcampus.ac.za Overriding Example In the main method: 17 www.belgiumcampus.ac.za Virtual and Overridden Methods Abstract and Overridden methods Virtual methods are meant to be re- An abstract class will usually contain implemented in derived classes. The abstract methods. In an abstract class a C# language provides method which has a keyword "abstract" the override modifier for this purpose. and doesn't provide any implementation This keyword specifies that a method is called an abstract method. replaces its virtual base method. The implementation logic of abstract Only if a method is declared virtual, methods has to be provided by the child derived classes can override this classes or derived classes. Child classes method if they are explicitly declared use keyword "override" with same method to override the virtual base class name (as abstract method name) to method with the override keyword. provide further implementation of abstract methods. 18 www.belgiumcampus.ac.za System.Object Class In C#, when we create a class, it is automatically inherits from System.Object class. The Object class is the base class for all the classes in.NET Framework. It is present in the System namespace. Every method defined in the Object class is available in all objects in the system. Every class in C# is directly or indirectly derived from the Object class. Derived classes can and do override some of these methods: i. Object.Equals - Supports comparisons between objects. ii. Object.GetHashCode - Generates a number corresponding to the value of the support the use of a hash table. iii. Object.ToString - Manufactures a human-readable text string that describes an the class. https://www.geeksforgeeks.org/c-sharp-object-class/ 19 www.belgiumcampus.ac.za System.Object Class Equals Overloaded: Equals(object obj) Determines whether the specified Object is equal to the current Object. Equals Overloaded: Equals(object objA, object objB) Determines whether the specified Object instances are considered equal. GetHashCode Serves as a hash function for a particular type, suitable for use in hashing algorithms and data structures like a hash table. GetType Gets the Type of the current instance. ReferenceEquals Determines whether the specified Object instances are the same instance. ToString Returns a String that represents the current Object. 20 www.belgiumcampus.ac.za ToString() Every class implicitly inherits the Object class. Therefore, every object in C# gets the ToString method, which returns a string representation of that object. For example, all variables of type int have a ToString method, which enables them to return their contents as a string. ToString() Returns a String that represents the current Object. This means we need to describe to C# which characteristics we would like to see in a string representation of a particular type of object. C# Syntax: public virtual string ToString(); The ToString method is a virtual method on the object type. Every type inherits from object. Thus you can use an override ToString method to change the implementation used. When the ToString method is called on the instance, the overridden method is used. 21 www.belgiumcampus.ac.za ToString() Examples Example 1 Example 2 In Main() 22 www.belgiumcampus.ac.za Learning Objectives What are Enums Using Enums as menus in Console Applications Exercises 2 www.belgiumcampus.ac.za Enum Concept An enum is a special "class" that represents a group of constants (unchangeable/read-only variables). An enum (or enumeration type) is used to assign constant names to a group of numeric integer values. Since enums are types, you create an enum just like you do a class, but the difference is you use the enum keyword (instead of class). Both classes and enums have members, but enum members are called items. You separate enum items with a comma. Enums are mostly used when you want to generate a ‘menu’ in a console application 3 www.belgiumcampus.ac.za Declaring Enums Syntax is as follows: Enums are strongly typed constants. If you have a number of constants that are logically related to each other (e.g, days of the week), then you can group together these constants in an enumeration. The main benefit of this is that constants can be referred to in a consistent, expressive and type safe way. 4 www.belgiumcampus.ac.za Enums Example Example: 5 www.belgiumcampus.ac.za Enums Values By default, the first item of an enum has the value 0. The second has the value 1, and so on. To get the integer value from an item, you must explicitly convert the item to an int. You can also assign your own enum values, and the next items will update the number accordingly: 6 www.belgiumcampus.ac.za Enums Example In our Main(), we can print out any day of our choosing from the enumeration list: 7 www.belgiumcampus.ac.za Enums in a Switch Statement We can use an enum in creating a menu in console. We make use of a switch statement. Enums are often used in switch statements to check for corresponding values. Example: Create a menu driven application that produces the following menu output: 8 www.belgiumcampus.ac.za Enums in a Switch Statement Solution: 9 www.belgiumcampus.ac.za Enums in a Switch Statement Solution: 10 www.belgiumcampus.ac.za Enum Summary Enums lend themselves to more maintainable code because they are symbolic, allowing you to work with integral values but using a meaningful name to do so. Enums are value types, which means they contain their own value, can’t inherit or be inherited from, and assignment copies the value of one enum to another Why And When To Use Enums? Use enums when you have values that you know aren't going to change, like month days, days, colors, deck of cards, etc. http://csharp-station.com/Tutorial/CSharp/Lesson17 11 www.belgiumcampus.ac.za Learning Objectives Understanding delegates Delegates vs. Function Pointers Use of delegates Type of information a delegate stores Two types of delegates Declaring delegates and working with different types of delegates. 2 www.belgiumcampus.ac.za Background Think of an everyday GUI (website or mobile App): Method1 event1 handles event2 Event Handler [Method Chooser] event2 Method3 handles event1 3 www.belgiumcampus.ac.za What is a delegate A delegate is a reference type variable that holds the reference to a method. The reference can be changed at runtime. Delegates are objects that contain information about the function rather than data. We can encapsulate a reference to the method inside the delegate object. A delegate is like a pointer to a function. All delegates are implicitly derived from the System.Delegate class. 4 www.belgiumcampus.ac.za Declaring a delegate A delegate can be declared using the delegate keyword followed by a function signature as shown below: Example: 5 www.belgiumcampus.ac.za Uses of Delegates GUI code uses delegates to handle events, such as button clicks, window moves. Using the delegate allows you do CHOOSE the proper function/method to call whenever an event occurs. Think of how many events occur on Facebook website (liking, emojis, comments, zooming, tagging, sharing etc.) Each of these are EVENTS that will be occurring on the page, and each has a method that has to be invoked, so as to handle the event. This event handler, is called a Delegate. 6 www.belgiumcampus.ac.za Example: Lets create the following methods: "{0, -12:N0}" means: for the first argument (variable), left align, 12 character wide column, formatted as a number, 0 decimal places. {0:C} means: for the first argument (variable), format as a currency https://www.tutlane.com/tutorial/csharp/csharp-string-format-method http://www.java2s.com/Tutorial/CSharp/0100__String/Stringformat0C.htm 7 www.belgiumcampus.ac.za Example… There are three steps in using delegates. These include: declaration, instantiation, and invocation. 1) Declaration: We then create a delegate that will point to the two methods, definition: #NB: You declare the delegate inside the class, but outside the methods and Main () method. A delegate can only refer to a method which has the same signature (return type and parameter list) as that of the delegate. 8 www.belgiumcampus.ac.za Invoking Delegates The delegate can be invoked like a method because it is a reference to a method. Invoking a delegate will in-turn invoke a method which is referred to. The delegate can be invoked in two ways: a) Using a () operator b) Using the Invoke() method 9 www.belgiumcampus.ac.za Example… 2) Instantiation: In the Main() method we instantiate an object (obj) of type numDelegate (our delegate name). We point it to the method that is supposed to “do something”. 3) Invocation: Use the object with the argument (the event) 10 www.belgiumcampus.ac.za Example 2: Say we have a class containing two methods: Using the syntax: delegate we create 2 delegates: 11 www.belgiumcampus.ac.za Example 2: Declare a delegate object with a signature that exactly matches the method signature of the method that you are trying to encapsulate otherwise the delegate will not be able to reference that method. So exact matching of methods for both delegate examples above will be: Name of delegate Name of method being pointed to, by delegate Name of class containing methods Object of delegate 12 www.belgiumcampus.ac.za Another way You can also use a delegate to point to a method using the following syntax: You can also use an object of the class, to point to a method using the following syntax: But then your method must be a non-static method 13 www.belgiumcampus.ac.za Types of Delegates 1. Single Cast Delegate: it represent one method. Single cast delegate Method() 2. Multi Cast Delegate: it represent more than one method. Multicast delegates hold more than one method references. Multicast delegates return type should be void. 14 www.belgiumcampus.ac.za Example: Multicast Delegates A delegate that can point to multiple methods is known as a multicast delegate. We use of the delegate instance, we have used the += operator to assign the delegate to multiple methods that have identical signature. Say we have 3 methods that accept one parameter each: 15 www.belgiumcampus.ac.za Example: Multicast Delegates We can then declare our delegate: In Main(), use a multicast delegate object: 16 www.belgiumcampus.ac.za Multicasting of a Delegate Delegate objects can be composed using the "+" operator. A composed delegate calls the two delegates it was composed from. Only delegates of the same type can be composed. The "-" operator can be used to remove a component delegate from a composed delegate. A delegate can be seen as a placeholder for a/some method(s). By defining a delegate, you are saying to the user of your class, "Please feel free to assign, any method that matches this signature, to the delegate and it will be called each time the delegate is Delegates are useful to offer to the user of your objects some ability to customize their behavior. Most of the time, you can use other ways to achieve the same purpose and I do not believe you can ever be forced to create delegates. It is just the easiest way in some situations to get the thing done. You can also use a delegate to send a method as a parameter to another method. 17 www.belgiumcampus.ac.za Where are delegates used? The most common example of using delegates is in events. You define a method that contains code for performing various tasks when an event (such as a mouse click) takes place. This method needs to be invoked by the run time when the event occurs. Hence this method, that you defined, is passed as a parameter to a delegate. Delegates also can invoke methods Asynchronously. 18 www.belgiumcampus.ac.za Important Information: 1. The return type and signature of delegates should be the same as the method we want to encapsulate. 2. It is not necessary to use delegates with parameters; we can use delegates with parameters and without parameters. 3. We can use static or non-static methods; In the case of static methods we encapsulate the method with the class name and in the case of a non-static method we first make the object of the class and then we use a method attached to the 19 www.belgiumcampus.ac.za Delegate Return type Delegate declaration determines the methods that can be referenced by the delegate. A delegate can only refer to a method which has the same signature (meaning return type and parameter list) as that of the delegate. For example, consider a delegate: public delegate int MyDelegate (string s); The delegate above can be used to reference any method that has a single string parameter and returns an int type variable. 20 www.belgiumcampus.ac.za Difference between Single-Cast and Multicast Delegates Single-Cast Delegates: Derived directly from System.Delegate Invocation list contains only one method. Multicast Delegates: Derived from System.MulticastDelegate Invocation list may contain multiple methods. 21 www.belgiumcampus.ac.za Exercise: Create a class called Calculations which houses two methods, an add() and a multiply(). Add() must take 2 parameters and add them together, whilst multiply also takes two parameters and multiplies them together. Use a multicast delegate to show how you will invoke the two methods, and produce the following output: Utilize the values 4 and 2 for Multiply method Utilize the values 10 and 12 for Add method. 22 www.belgiumcampus.ac.za Learning Objectives What is an event Using delegates with events Event processing model Event notification methods Event handler method Declaring an event Invoking an event Hooking up to an event 2 www.belgiumcampus.ac.za Events: The Concept “In general terms, an event is something special that is going to happen. For example, Microsoft launches events for developers, to make them aware of the features of new or existing products. Microsoft notifies the developers about the event by email or other advertisement options. So in this case, Microsoft is a publisher who launches (raises) an event and notifies the developers about it and developers are the subscribers of the event and attend (handle) the event.” Events are a mechanism for communication between objects. This means, when something happens inside an object, it can notify other objects about that. Why do we need that? It helps us build loosely coupled applications. A loosely couple application is one that its components and classes are not tightly coupled together. A loosely coupled application is easy to extend without breaking or changing, one or more of its existing capabilities. Lets look at a scenario. 3 www.belgiumcampus.ac.za Scenario! Lets say we have a government arm called the South African Highway Service (SAHS), a company responsible of building all major highways in SA. When ever this company is building a road, it sub-contracts other small companies, called contractors. So, when a road is being build, SAHS needs to notify all contractors in its mailing list, that it needs certain services. It sends an email, saying SAHS needs grader contractors, tar contractors, paint-job contractors etc. Only contractors who are in their mailing list will get the notification via email. Representing it as a class, say we have a method called buildHighway(), that builds a highway: During building of road, if SAHS needs a sub-contractor, it sends an email 4 www.belgiumcampus.ac.za Changes occur! Lets say in future, there is an additional method of notifying sub-contractors that SAHS can utilize, say texting. It means that we can add an extra line of code for sending using text: In this case, we are now modifying out SAHS class. The problem is, now that we added textService code, the buildHighway() method has changed. Which means it has to be recompiled. Which means the SAHS class also has to be recompiled. Which also means, any other classes that are depended on this SAHS class, have to be recompiled, and re-deployed. We call this problem, Tight-Coupling. The classes and objects are tightly coupled together, and as software developers, we want to reduce this problem. 5 www.belgiumcampus.ac.za What are Events? Events are basically a user action like key press, clicks, mouse movements, etc., or some occurrence like system generated notifications. Once an action occurs, a message can be sent by an object to indicate that particular action is going to/has happened. This message is the Event. Applications need to respond to events when they occur. For example, I/O interrupts. Events are used for inter-process communication. 6 www.belgiumcampus.ac.za Solution!!! We want to design our programs such that, when we have changes to our apps, that change has minimal impact on the overall application. The problem with the code is that by adding extra code like above, we may accidentally break something along the way. That’s where Events comes to the rescue. We can use events to solve this problem: Now, we can have our SAHS class publish an event (contactContractors) and have the sendMessage class to subscribe to that event. In this case, SAHS is the event publisher, and sendMessage is an event subscriber. 7 www.belgiumcampus.ac.za Event Subscribers and Publishers SAHS class knows absolutely nothing about sendMessage class. Which means, if we want to extend/modify the program in future, and add the capability of sending text when a subcontractor is subcontractor is needed, we simply add an additional sendText class, which also subscribes to the subscribes to the contactContractors event. Subscribers are Event Handlers (classes/methods that handle events in different ways) 8 www.belgiumcampus.ac.za Event Subscribers and Publishers Events enable a class/object to notify other classes/objects when something of interest occurs. The class that sends (or raises) the event is called the publisher and the classes that receive (or handle) the event are called subscribers. In this model, you have publishers who will do some logic and publish an "event." Publishers will then send out their event only to subscribers who have subscribed to receive the specific event. Rules of creating Events Events are based on delegates Objects of events can subscribe and unsubscribe from events 9 www.belgiumcampus.ac.za So, now we have our _mailService.Send() and _textService.Send() methods in their respective classes, our subscribers (sendMessage and sendText). In our SAHS class, we can simply have: Instead of calling our _mailService.Send() and _textService.Send() as we did before, we now simple call the contactContractors() method. This method’s job now is to simply notify all subscribers, by raising an event which subscriber classes have subscribed to. Now, we can even add more subscribers, (say SAHS now wants to send mail, text and also process calls to its sub-contractors) without changing anything in this code. 10 www.belgiumcampus.ac.za For SAHS to notify its subscribers of an event, it needs to send a message to them. This means invoking a method in the subscriber classes ( _mailService.Send() and _textService.Send()). Publisher class now needs an agreement with subscriber classes, on a way to set up the methods that will act as method handlers (in subscriber classes). This agreement is acts like a pointer to the event handler methods, that both the publisher and the subscriber agree upon. It is a method, with a specific signature: 11 www.belgiumcampus.ac.za For SAHS to notify its subscribers of an event, it needs to send a message to them. This means invoking a method in the subscriber classes ( _mailService.Send() and _textService.Send()). Publisher class now needs an agreement with subscriber classes, on a way to set up the methods that will act as method handlers (in subscriber classes). This agreement is acts like a pointer to the event handler methods, that both the publisher and the subscriber agree upon. It is a method, with a specific signature: 12 www.belgiumcampus.ac.za Enter delegates In this case, the SAHS class knows nothing about the sendMessage and sendText classes. It is completely de-coupled from them. Now, all it knows is a method, contactContractors(), which it invokes whenever it needs a contactor. How that method works is also hidden away from the SAHS class. The implementation depends on the subscriber class. For a subscriber to know which method to call, it uses delegates 13 www.belgiumcampus.ac.za Creating Events and delegates Now, all the SAHS class knows is a method, contactContractors(), which it invokes whenever it needs a contactor. How that method works is also hidden away from the SAHS class. The implementation depends on the subscriber class. For a subscriber to know which method to call, it uses delegates. Syntax: // 1 – declaring delegate (can have arguments) // 2 - defining an event based on the delegate signature 14 www.belgiumcampus.ac.za The Event Processing Model An event producer (or publisher) An event consumer (or subscriber) A delegate is a way of telling C# which method to call when an event is triggered. They are created and used in the publisher, to point to the method in the subscriber, which will handle the raised event. Delegates are good, as you can notify several methods that an event has occurred (Multicast delegate). 15 www.belgiumcampus.ac.za Implementing Custom Events Example: We create a class called SAHS. We add a method to build roads in SAHS: 16 www.belgiumcampus.ac.za Implementing Custom Events Once we see that we not need a contractor, we must to raise an event, that lets subscribers know, that SAHS needs contractors. In this case, we create a delegate and an event to be raised in the SAHS class: 17 www.belgiumcampus.ac.za Implementing Custom Events We now need to raise the event. But to raise the event, we need it to be in a method called contactContractors(): 18 www.belgiumcampus.ac.za Implementing Custom Events In the subscriber classes, we need to give implementations of the contactContractors method(): 19 www.belgiumcampus.ac.za Implementing Custom Events In Main method, we: 20 www.belgiumcampus.ac.za Implementing Custom Events Output: 21 www.belgiumcampus.ac.za Implementing Custom Events To implement custom event processing in your programs you need to understand how to create the following component types: Delegates Event Generating Objects (publishers) - Events - Event Notification Methods Event Handling Objects (subscribers) - Event Handler Methods - You will also need to know how to pass information related to the event between the event generating object and the subscriber object - The EventArgs class can be used as-is or sub classed - The EventArgs class captures generic information about an object and the event that occurred 22 www.belgiumcampus.ac.za Delegates and Events with parameters We can declare delegates we create for events to have a signature with parameters: public delegate void EventHandler (Object sender, EventArgs e) Represents a method that has two parameters, the first one being of type Object and the second being of type EventArgs. Its return type is void. Any method, so long as its signature matches that expected by the delegate, can be handled by the delegate. The delegate object contains the subscriber list. It is actually implemented as a linked list where each node of the list contains a pointer to a subscriber’s event handler method. 23 www.belgiumcampus.ac.za Event Notification Method In addition to an event field, a publisher will have a method whose job it is to start the subscriber notification process when the event in question occurs. An event notification method is just a normal method. It usually has a parameter of EventArgs or a user-defined subtype of EventArgs. But it can have any number and type of parameters you require. Event Handler Method An event handler methods is an ordinary method that is registered with a publisher’s event. The event handler method’s signature must match the signature required by the publisher’s event delegate. 24 www.belgiumcampus.ac.za Subscriber: A subscriber is a class that registers its interest in a publisher’s events. A subscriber class contains one or more event handler methods. Invoking an event Once a class has declared an event, it can treat that event just like a field of the indicated delegate type. The field will either be null, if no client has hooked up a delegate to the event, or else it refers to a delegate that should be called when the event is invoked. Thus, invoking an event is generally done by first checking for null and then calling the event. if (ChangeNum != null) { ChangeNum(); } Invoking an event can only be done from within the class that declared the event. 25 www.belgiumcampus.ac.za Hooking up to an event www.belgiumcampus.ac.za Learning Objectives Threading (The concept) Thread States Multi-threading Task manager System.Threading Multi-threading implementation Examples Deadlock in C# Threading 2 www.belgiumcampus.ac.za Threading Concept Threading enables us to execute multiple things "at the same time" on the same computer. When a user starts an application, memory and a whole host of resources are allocated for the application. Doing multiple things at the same time on a single processor isn't actually possible, but the computer does this "virtually" through the concept of threads. Each thread has its own "stack" of executable code that it is running and in modern day systems the operating system "marshals" the threads into and out of the processor. The physical separation of this memory and resources is called a process. An application may launch more than one process. 3 www.belgiumcampus.ac.za Threading Concept Each process has an execution sequence used by the computer's CPU. This execution sequence is known as a Thread. This thread is defined by the registers in use on the CPU, the stack used by the thread, and a container that keeps track of the thread's state (the Thread Local Storage, TLS). A thread is defined as the execution path of a program. Threads improve performance. The advantage of threading is the ability to create applications that use more than one thread of execution, for concurrent processing. 4 www.belgiumcampus.ac.za Threading in C# When ever we run a program in Main(), threads are created for us by the Operating System in the background. Say we call another method outside the Main() method, if we invoke it in Main(), the O.S tries to utilize threads to run both pieces of code, by sharing CPU resources between them. Example: Main thread run. Sequence depends on O.S Other threads. Need to be run in Main()

Use Quizgecko on...
Browser
Browser