CIS 260 C# Chapter 12: How to Create and Use Classes 1. An Introduction to Classes 1.1. How classes can be used to structure an application A class is a template to define objects with their properties and functionality Windows forms applications: three-layered class architecture Presentation layer Main Windows form class Other form classes Middle layer Business classes Database layer Database classes Database Presentation layer controls the user interface Database layer handles the application s data processing Middle layer represents business entities such as customer, product, etc 1
Advantages of this architecture: - Allows the development to be spread among team members - Allows classes to be shared among applications - Allows different layers to run on different servers to improve performance 1.2. Class members: properties, methods, events Properties defined as private variables Methods define the functionality of the class objects and relations to other objects. Special method: constructor used to create an object of the class responded to. Events signals sent by the object that something has happened and has to be Encapsulation: a fundamental concept in OOP Refers to the capability to use an object without knowing its internal structure and how its methods are implemented Types of class members Property Method Constructor Delegate Event Field Constant Indexer Operator Class Represents a data value associated with an object instance. An operation that can be performed by an object. A special type of method that s executed when an object is instantiated. A special type of object that s used to wire an event to a method. A signal that notifies other objects that something noteworthy has occurred. A variable that s declared at the class level. A constant. A special type of property that allows individual items within the class to be accessed by index values. Used for classes that represent collections of objects. A special type of method that s performed for a C# operator such as + or ==. A class that s defined within the class. 2
1.3. Object instantiation An object is an instance of a class. Instantiation - the process of creating an object. Classes that instantiate objects define types (the type is the name of the class). Object declaration: Memory is reserved for the variable that will contain the address of the memory where the object properties are located. This is a reference variable. Example: Product product1; product1 is a reference variable. It will contain the memory address where the specific properties of the object product1 of type Product will be stored. The declaration statement above stores null in the variable product1 Object instantiation: A memory block is reserved for the properties of the object and its address is stored in the object variable. The constructor is invoked and its code is executed. It usually initializes the object properties. There may be more than one constructor. Example: public class Product private string code; private string description; private decimal price; public Product() public Product(string code, string description, decimal price) this.code = code; this.description = description; this.price = price; Instantiation of two objects of type Product: Product product1, product2; product1 = new Product("CS10", "Murach's C# 2010", 54.50m); product2 = new Product("VB10", "Murach's Visual Basic 2010", 54.50m); 3
Declaration and instantiation can be combined in one statement: Product product1 = new Product("CS10", "Murach's C# 2010", 54.50m); 2. How to Create a Class Use Project Add Class Type the name of the class A class file is added to the project and will appear in the solution window The namespace and class blocks are automatically added. Then you type the code in the class block Class fields: variables defined at class level, available to the entire class Instance variables: contain information about a particular instance of that class Static variables: contain information that is available to all instances of the class Read-only fields: cannot be changed when the program runs, set at run time (constants are set at compilation) keyword: readonly E.G: public readonly int Limit = 100; Access modifiers: - Public: available to other classes - Private: available only within the class 3. How to Code Properties public type PropertyName get get accessor code set set accessor code Example: public string Code get return code; // code is a private variable that // holds the value of the property set code = value; // value is a keyword used to pass the value // to the variable code Example of usage: string myvariable = product1.code; // invokes the get method myvariable = myvariable + V1 ; product1.code = myvariable; // invokes the set method 4
Auto-implemented property when no additional code is necessary public string Code get; set; 4. How to Code Methods public returntype MethodName ([parameterlist]) statements Overloading methods: Same name, different parameter lists 5. How to Code Constructors Constructors are methods that assign values to the instance variables. They are invoked upon object instantiation (using the operator new) If the constructor does not have parameters, or if there is no constructor, C# assigns default values (numbers are 0, Boolean variables are false, objects are null) Example: public Product(string code, string description, decimal price) this.code = code; this.description = description; this.price = price; The keyword this shows that the properties listed are properties of the current class. 6. How to Code Static Members Static members are used without referring to an object instance. The keyword static is used to define static members a. Static classes Static classes contain only static methods (see (b) below). Example: public static class Validator public static bool IsPresent(TextBox textbox)..// other static methods 5
b. Static methods When defined in a static class, static methods are referred to by the name of the class: if (Validator.IsPresent(textbox)).//statements When static members are defined in a non-static class, they can be shared by all other instances of the class. 7. How to Create Code Stubs Generate From Usage feature can be used to generate code stubs for any undefined class, constructor, property, method, field, enumeration, structure or interface from the current location in your code. 7.1. A class stub A class stub can be generated from the code that uses that class. Example: Suppose you want to instantiate an object of a class that does not exist yet. School school = new School( ); Since the School class does not exist, you will see a syntax error. Open the smart tag menu for the class name (when you position the cursor on the class name, an icon will appear bellow the name, click on it and the menu will open). Select the Generate class option. A class named School will be generated and shown as School.cs in the Solution explorer window. class School Note that no access modifier will be given. It is up to the programmer to add public in front of the keyword class. 7.2. A method stub When you write code that refers to an undefined method, you can use the smart tag menu (similar to creating a stub for a class) to create a stub for that method. 6
Example: School school = new School( ); string schooladdress = school.getaddress(); Suppose GetAddress( ) is not defined. With the smart tag menu you can generate a stub for that method: string GetAddress() throw new NotImplementedException (); Note that the return type is automatically determined by the statement that calls the method. Note that no access modifier is supplied, you have to add it, e.g. public string GetAddress(). If you run the code, a run-time error Unhandled exception will occur. To avoid the run-time error, you should use try-catch around the statement that calls the method: try // other statements string schooladdress = school.getaddress(); catch (Exception ex) System.Windows.Forms.MessageBox.Show(ex.Message); The message that you will get is: The method or operation is not implemented. In order to get a more meaningful message, you may change the argument in the throw statement: throw new NotImplementedException("The method GetAddress in School class is not implemented"); 7
Learning Objectives After studying Chapter 12, you should be able to: 1. List and describe the three layers of a three-layered application. 2. Describe these members of a class: constructor, method, field, and property. 3. Explain how instantiation works. 4. Describe the concept of overloading a method. 5. Explain what a static member is. 6. Describe the basic procedure for using the Generate From Usage feature to generate code stubs. 8