Download presentation
Presentation is loading. Please wait.
1
How to Create and use Classes and Structures
Based on Murach (Ch 12) and Deitel (Ch 4-6)
2
Objectives Applied Given the specifications -> develop the application and its classes. Use the Solution Explorer and the CodeLens feature to browse the classes in a solution. Use class diagrams and the Class Details window to review Use the Peek Definition window to display and edit the code for a member in another class from within the class that refers to it. Knowledge List and describe the three layers of a three-layered application. Describe these members of a class: constructor method field property
3
Objectives cont. Describe the concept of encapsulation.
Explain how instantiation works. Describe the main advantage of using object initializers. Describe the concept of overloading a method. Explain what a static member is. Explain how auto-implemented properties work. Explain how expression-bodied properties and methods work. Describe the basic procedure for using the live code analysis feature to generate code stubs. Describe the difference between a class and a structure.
4
The architecture of a three-layered application (MVC*)
Functions to present Can be a separate server1 developers Can be server2 Functions to process Foundations for dlls Functions to preserve Can be server3
5
Three Tier Architecture
A 3-tier architecture to separate the application’s user interface business rules database processing. The classes in the presentation layer control the application’s user interface. For a Windows Forms application, the user interface consists of the various forms that make up the application. The classes in the database layer handle all of the application’s data processing. .
6
Three Tier Architecture (Middle layer)
. The classes in the middle layer, (the business rules layer), act as an interface between the classes in the presentation and database layers. These classes can represent business entities, such as customers or products, or they can implement business rules, such as discount or credit policies. When the classes in the middle layer represent business entities, the classes can be referred to as business classes, and the objects that are created from these classes can be referred to as business objects. Often, the classes that make up the database layer and the middle layer are implemented in class libraries that can be shared among applications.
7
Class members Properties Methods Events Constructors to create objects
just a special type of method that’s executed when an object is created.
8
Ex: ProductManagement Project The members of a Product class
Properties Description Code A string that contains a code that uniquely identifies each product. A string that contains a description of the product. Price A decimal that contains the product’s price. Method GetDisplayText( sep ) Returns a string that contains the code, description, and price in a displayable format. The parameter is a string that’s used to separate the elements.
9
Ex: ProductManagement The members of a Product class Constructors
10
Methods and Events A method is a function which executes something in it is called. It can be called at any time. A event is a result of a action performed by the user like click, hover, drag, re-size etc. There are event handlers. Basically these are methods that are called when a event happens.
11
Methods and Events (C#). More in ch 13.
C# Events are a specific form of delegates. (C++) a delegate is a function ("method") pointer - it points to some code in memory. When you call the pointer as a method, you actually call the method at the address the pointer points to. This is necessary to provide decoupling between the caller and the callee - so you don't have to have all methods ready when you publish code that calls them (which, wouldn't be possible - the Forms controls developers can't possibly know the code that needs to be called when a Button is pressed). You call the pointer, and the other developer sets it to an appropriate memory address later. Delegates and Events however, have other advantages over plain function pointers - you can be sure that it will point to a good-looking method, taking the correct number and type of arguments and returning the correct type.
12
Product class 3 properties: store the
code, description, and price for each product; a method GetDisplayText that returns a formatted string that contains the code, description, and price for a product; two constructors that create instances of the class.
13
General: Types of class members
*Most classes have highlighted
14
General: Types of class members cont.
15
Class and object concepts
An object is a self-contained unit that has properties, methods, and other members. A class contains the code that defines the members of an object. An object is an instance of a class, and the process of creating an object is called instantiation. Encapsulation is one of the fundamental concepts of object-oriented programming (OOP). It lets you control the data and operations within a class that are exposed to other classes. The data of a class is typically encapsulated within a class using data hiding. In addition, the code that performs operations within the class is encapsulated so it can be changed without changing the way other classes use it. Although a class can have many different types of members, most of the classes you create will have just properties, methods, and constructors.
16
Encapsulation A fundamental concept of object-oriented programming.
Lets the programmer hide, or encapsulate, some of the data and operations of a class while exposing others. For example, although a property or method of a Class can be called from other classes, its implementation is hidden within the class. That way, users of the class can think of it as a black box that provides useful properties and methods. This also means that you can change the code within a class without affecting the other classes that use it. This makes it easier to enhance or change an application because you only need to change the classes that need changing.
17
The Product class: Fields and constructors
namespace ProductMaintenance { 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; } class fields no-arg constructor zero argument 3-arg constructor
18
The Product class: The Code property
public string Code { get return code; } set code = value;
19
The Product class: The Description property
public string Description { get return description; } set description = value;
20
The Product class: The Price property
public decimal Price { get return price; } set price = value;
21
The Product class: The GetDisplayText method Method Overloading
Using default separator public string GetDisplayText() { return code + ", " + price.ToString("c") + ", " + description; } Using custom separator public string GetDisplayText(string sep) return code + sep + price.ToString("c") + sep + description;
22
Object Instantiation The process of creating an object from a class is called instantiation. You can creates as many instances as you want. Also, you can use object initializers. Object initializers let you assign values to any accessible fields or properties of an object at creation time without having to invoke a constructor followed by lines of assignment statements. Important! Class defines a reference type. That means that the variable that’s used to access an object contains the address of the memory location where the object is stored, not the object itself. In other words, the product1 variable holds a reference to a Product object, not an actual Product object.
23
Ex.: Instantiating Product Class
Code that creates these two object instances using constructors. Product product1, product2; product1 = new Product("CS15", "Murach's C# 2015", 56.50m); product2 = new Product("VB15", "Murach's Visual Basic 2015", 56.50m); Code that creates the object instances with object initializers product1 = new Product { Code = "CS15", Description = "Murach's C# 2015", Price = 56.50m }; product2 = new Product {Code = "VB15", Description = "Murach's Visual Basic 2015", Price = 56.50m };
24
Advantage: Object Initializers (more)
If Product has no 3-argument constructor Product p1 = new Product(); p1.Code=“ABC”; p1.Description = “some desc”; p1.Price = 50m; But! This can do it! Product p1 = new Product { Code = “ABC", Description = “some desc", Price = 50m };
25
The dialog box for adding a class (already known)
26
General: The dialog box for adding a class Project->Add New Item
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ProductMaintenance { class Product }
27
General: Examples of field declarations
A variable declared within class is called field. Instance variable is a field that’s defined in a class and is allocated when the object is instantiated. Access modifiers private int quantity; // A private field public decimal Price; // A public field ~ property public readonly int Limit = 90; // A public read-only field const is set at compile time; read-only at run-time write-only (exist, but not used)
28
Class Class SubClass SubClass ASSEMBLY Class public A protected B
internal C private D Class public A protected B internal C private D SubClass (outside package) public A protected B internal C private D SubClass public A protected B internal C private D ASSEMBLY Class (outside package) public A protected B internal C private D
29
Access Modifiers (MSDN C# Programming Guide)
public The type or member can be accessed by any other code in the same assembly or another assembly that references it. protected The type or member can be accessed only by code in the same class or struct, or in a class that is derived from that class. internal The type or member can be accessed by any code in the same assembly, but not from another assembly. protected internal 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. Access from another assembly must take place within a class declaration that derives from the class in which the protected internal element is declared, and it must take place through an instance of the derived class type. Note that: protected internal means "protected OR internal" (any class in the same assembly, or any derived class - even if it is in a different assembly). private The type or member can be accessed only by code in the same class or struct.
30
A Product class that uses public fields instead of Properties
public class Product { //class PUBLIC fields public string Code; public string Description; public decimal Price; public Product() { } public Product(string code, string description, decimal price) { this.Code = code; this.Description = description; this.Price = price; } public string GetDisplayText(string sep) return Code + sep + Price.ToString("c") + sep + Description; .. .
31
A Product class that uses Properties fields
public class Product { //class fields private string code; private string description; private decimal price; public Product() { } public string Code { get return code; } set code = value; … public Product(string code, string description, decimal price) this.Code = code; this.Description = description; this.Price = price; public string GetDisplayText(string sep) return code + sep + price.ToString("c") + sep + description; .. .
32
General: The syntax for coding a public property
public type PropertyName { [get { get accessor code }] [set { set accessor code }] } Example: a read/write property public string Code get { return code; } set { code = value; } Example: a read-only property public decimal DiscountAmount get discountAmount = subtotal * discountPercent; return discountAmount; set No
33
How to code properties (accessors and modifiers)
A property declaration specifies both the type and name of the property. In addition, a property is typically declared with the public access modifier so it can be accessed by other classes. The get accessor is executed when a request to retrieve the property value is made, and the set accessor is executed when a request to set the property value is made. If both get and set accessors are included, the property is called a read/write property. If only a get accessor is included, the property is called a read-only property. A write-only property, which has just a set accessor, but that’s uncommon. In most cases, each property has a corresponding private instance variable that holds the property’s value. In that case, the property should be declared with the same data type as the instance variable.
34
How to code properties (accessors and modifiers) Naming conventions.
It’s also common to use the same name for the property and the instance variable, but to use Camel notation for the instance variable name first word starts with a lowercase character. All words after that start with uppercase characters and to use Pascal notation for the property name each word starts with an uppercase character. Ex.: the name of the instance variable for the Code property is code. And a property named UnitPrice would have a corresponding instance variable named unitPrice. Because a get accessor returns the value of the property, it typically ends with a return statement that provides that value. However, get accessor can be more complicated than that. It can perform a calculation to determine the value that’s returned. The set accessor uses an implicit parameter named value to access the value to be assigned to the property. Typically. the set accessor simply assigns this value to the instance variable that stores the property’s value. It can perform more complicated processing if necessary. For example, it could perform data validation.
35
Get and Set A statement that sets a property value
product.Code = txtProductCode.Text; A statement that gets a property value string code = product.Code;
36
The syntax for coding a public method
public returnType MethodName([parameterList]) { statements } A method that accepts parameters public string GetDisplayText(string sep) return code + sep + price.ToString("c") + sep +description; An overloaded version of the method public string GetDisplayText() return code + ", "+price.ToString("c") + ", "+ description;
37
Ex: Method Overloading
public class Wine { . . . public int MyMethod(int x) return x; } public int MyMethod(int x, int y) return x+y; public int MyMethod(int x, float y) return x + (int)y; public int MyMethod(int x, int y, float z) return x + y + (int)z; public int MyMethod(int x, float z) return x + (int)z; Nope
38
Method Overloading cont.
public class Wine { . . . public int MyMethod(int x) return x; } public float MyMethod(int x) The signature of a method specifically does not include the return type, nor does it include the params modifier that may be specified for the right-most parameter.
39
Statements that call the GetDisplayText method
This way lblProduct.Text = product.GetDisplayText("\t"); lblProduct.Text = product.GetDisplayText(); IntelliSense feature lists overloaded methods
40
Constructors An overloaded constructor with no parameters SAME NAME AS CLASS public Product() { } An overloaded constructor with three parameters public Product (string code, string description, decimal price) this.Code = code; this.Description = description; this.Price = price; An overloaded constructor with one parameter public Product(string code) Product p = ProductDB.GetProduct(code); this.Code = p.Code; this.Description = p.Description; this.Price = p.Price; Statements that call these constructors Product product1 = new Product(); Product product2 = new Product("CS15“, "Murach's C# 2015", 56.50m); Product product3 = new Product(txtCode.Text);
41
Default values for instance variables
Strings are Object type
42
static Class Members
43
Static Classes vs Non-Static Classes
Static class Non-static class Contains only static members Can have static and non-static. Cannot be instantiated members Is sealed Cannot contain instance Constructors Static members can only refer to static
44
const, readonly and static readonly (const)*
The value of a const field is set to a compile time constant and cannot be changed at runtime Constants are declared as a field, using the const keyword and must be initialized as they are declared public class MyClass { public const double PI = ; }
45
const, readonly and static readonly (const)*
PI cannot be changed in the application anywhere else in the code as this will cause a compiler error Constants must be a value type (sbyte, byte, short, ushort, int, uint, long, ulong, char, float, double, decimal, or bool), an enumeration, a string literal, or a reference to null. Since classes or structures are initialized at run time with the new keyword, and not at compile time, you can't set a constant to a class or structure. Constants can be marked as public, private, protected, internal, or protected internal. Constants are accessed as if they were static fields, although they cannot use the static keyword. To use a constant outside of the class that it is declared in, you must fully qualify it using the class name.
46
const* Every constant declared in a class, but NOT inside a method of the class is implicitly static, so it’s a syntax error to declare such a constant with keyword static explicitly. class SomeClass { public static const int BUFFER_SIZE= 1024; }
47
const, readonly and static readonly (readonly)*
A read only member is like a const in that it represents an unchanging value. The difference is that a readonly member can be initialized at runtime, in a constructor as well being able to be initialized as they are declared. public class MyClass public class MyClass { { public readonly double PI = ; public readonly double PI; } public MyClass() { PI = } Can have different values depending on the constructor used.
48
const, readonly and static readonly (static readonly)
A readonly field can also be used for runtime constant: public static readonly uint l1 = (uint)DateTime.Now.Ticks; readonly members are not implicitly static, and therefore the static keyword can be applied to a readonly field explicitly if required. A readonly member can hold a complex object by using the new keyword at initialization. static readonly field is set at run time, and can thus be modified by the containing class
49
What is the difference between const and static readonly?
class Program { public static readonly Test test = new Test(); public static void Main(string[] args) { test.Name = "Program"; test = new Test(); // Error: A static readonly field cannot be // assigned to (except in a static constructor or // a variable initializer) } } class Test public string Name; On the other hand, if Test were a value type, then assignment to test.Name would be an error.
50
Validator class contains static members
public static class Validator { private static string title = "Entry Error"; //declared static public static string Title //must be static too get return title; } Set title = value; …
51
Validator class contains static members cont.
public static bool IsPresent(TextBox textBox) { if (textBox.Text == "") MessageBox.Show(textBox.Tag + " is a required field.", Title); textBox.Focus(); return false; } return true;
52
Code that uses static members (general approach)
if ( Validator.IsPresent(txtCode) && Validator.IsPresent(txtDescription) && Validator.IsPresent(txtPrice) ) isValidData = true; else isValidData = false; A using directive for the Validator class using static ProductMaintenance.Validator;
53
frmNewProduct private bool IsValidData() { return Validator.IsPresent(txtCode) && Validator.IsPresent(txtDescription) && Validator.IsPresent(txtPrice) && Validator.IsDecimal(txtPrice); }
54
Product Maintenance (implementation black box for now)
Retrieves product info from an xml file Displays it in a list box Lets the user add or delete products
55
The Product Maintenance form (frmProductMain)
New Product Form (frmNewProduct)
56
Tag property (ch. 10) The Tag property provides a convenient way to pass data between forms in a multi-form application. A dialog box can set its Tag property before it returns control to the main form. Then, the main form can get the data from this property and use it as necessary. Because the Tag property is an object type, you must explicitly cast it to the appropriate type to retrieve the data it contains. Or, you can use the ToString method to convert the data to a string.
57
Tag property (ch. 10) MSDN Any type derived from the Object class can be assigned to this property. If the Tag property is set through the Windows Forms designer, only text can be assigned. A common use for the Tag property is to store data that is closely associated with the control. For example, if you have a control that displays information about a customer, you might store a DataSet that contains the customer's order history in that control's Tag property so the data can be accessed quickly.
58
The Tag property settings for the text boxes on the New Product form
59
Product class (again)
60
ProductDB class Note Method Description
You don’t need to know how the ProductDB class works. You just need to know about its methods so you can use them in your code. Method Description GetProducts() A static method that returns a List<> of Product objects from the Products file. SaveProducts(list) A static method that writes the products in the specified List<> of Product objects to the Products file.
61
Validator class Property Description Title A static string that contains the text that’s displayed in the title bar of a dialog box that’s displayed for an error message. Static method Returns a Boolean value that indicates whether… IsPresent(textBox) Data was entered into the specified text box. IsInt32(textBox) An integer was entered into the specified text box. IsDecimal(textBox) A decimal was entered into the specified text box. IsWithinRange(textBox, min, max) The value entered into the text box is within the specified range.
62
The code for the Product Maintenance form
public partial class frmProductMain : Form { public frmProductMain() InitializeComponent(); } private List<Product> products = null; private void frmProductMain_Load(object sender, EventArgs e) products = ProductDB.GetProducts(); FillProductListBox(); private void FillProductListBox() lstProducts.Items.Clear(); foreach (Product p in products) lstProducts.Items.Add(p.GetDisplayText("\t"));
63
The code for the Product Maintenance form cont.
private void btnAdd_Click(object sender, EventArgs e) { frmNewProduct newProductForm = new frmNewProduct(); Product product = newProductForm.GetNewProduct(); if (product != null) products.Add(product); ProductDB.SaveProducts(products); FillProductListBox(); } private void btnDelete_Click(object sender, EventArgs e) int i = lstProducts.SelectedIndex; if (i != -1) Product product = (Product)products[i]; string message = "Are you sure you want to delete “ + product.Description + "?"; DialogResult button = MessageBox.Show(message, "Confirm Delete", MessageBoxButtons.YesNo); if (button == DialogResult.Yes) products.Remove(product);
64
Exit private void btnExit_Click(object sender, EventArgs e) { this.Close(); }
65
frmNewProduct public partial class frmNewProduct : Form {
public frmNewProduct() InitializeComponent(); } private Product product = null; public Product GetNewProduct() this.ShowDialog(); return product; private void btnSave_Click(object sender, EventArgs e) if (IsValidData()) product = new Product(txtCode.Text, txtDescription.Text, Convert.ToDecimal(txtPrice.Text)); this.Close();
66
frmNewProduct cont. private bool IsValidData() { return Validator.IsPresent(txtCode) && Validator.IsPresent(txtDescription) && Validator.IsPresent(txtPrice) && Validator.IsDecimal(txtPrice); } private void btnCancel_Click(object sender, EventArgs e) this.Close();
67
Validator public static class Validator { private static string title = "Entry Error"; public static string Title get return title; } set title = value; public static bool IsPresent(TextBox textBox) if (textBox.Text == "") MessageBox.Show(textBox.Tag + " is a required field.", Title); textBox.Focus(); return false; return true; Since the Validator class shown in this figure contains only static members, the static keyword has been used to declare the entire class as a static class. This prevents you from accidentally coding any non-static members for this class or from creating an object from this class. If you attempt to write such code, this class won’t compile.
68
Validator cont. public static bool IsDecimal(TextBox textBox) { decimal number = 0m; if (Decimal.TryParse(textBox.Text, out number)) return true; } else MessageBox.Show(textBox.Tag + " must be a decimal value.", Title); textBox.Focus(); return false;
69
More on set and get [] - optional
The syntax for coding auto-implemented property public type PropertyName { get; [set;] } [= value] Example: an auto-implemented property with both get and set accessors public string Code { get; set; } Example: an auto-implemented property with a get accessor and an initial value public string Code { get; } = "CS15";
70
set and get more auto-implemented
A statement that sets the value of an auto-implemented property product.Code = txtProductCode.Text A statement that gets the value of an auto-implemented property string code = product.Code;
71
read-only property and Expression Body
public decimal DiscountAmount { get return subtotal * discountPercent; } //no set The same property using an expression body public decimal DiscountAmount => subtotal * discountPercent; Lambda operator (“goes to”) Read more online, for example,
72
Method returning the value of an expression
public string GetDisplayText(string sep) { return code + sep + price.ToString("c") + sep + description; } The same method using an expression body public string GetDisplayText(string sep) => code + sep + price.ToString("c") + sep + description;
73
Method executing a single statement
public void DisplayProduct() { MessageBox.Show("Code: " + code + "\n" + "Price: " + price.ToString("c") + "\n“ + "Description: " + description, "Product"); } The same method using an expression body public void DisplayProduct() => "Price: " + price.ToString("c") + "\n" + "Description: " + description, "Product");
74
Using live code analysis to generate a class
Using Quick Actions… (right click)
75
Using live code analysis to generate a method stub
76
The Product class in the Solution Explorer with references to the Price property displayed*
*Community Edition 2017 doesn’t have the CodeLens feature that lets you display references.
77
A class diagram that shows two of the classes
To create a class diagram right click on project name in Solution Explorer->ProductMaintenance->RightClick->View ->View Class Diagram
78
A Peek Definition window with the code for the GetDisplayText method
Point to GetDisplayText, right click->Peek View
79
Structs vs Classes Both are user-defined types
Both can implement multiple interfaces Both can contain Fields, constants, events, arrays Methods, properties, indexers, operators, constructors Both can have Private Fields Both can have Public Properties Both can have constructors Both can have methods Example of struct: System.Int32 is a struct (ex.)
80
Classes and Structs cont.
class CPoint { int x, y; ... } struct SPoint { int x, y; ... } CPoint cp = new CPoint(10, 20); SPoint sp = new SPoint(10, 20); 10 sp 20 cp CPoint 10 20
81
Class Struct Reference type (holds a reference to an object in memory)
Value type (holds value in memory where it is declared) Can inherit from any non-sealed reference type No inheritance (inherits only from System.ValueType) Can have a destructor No destructor Can have user-defined parameterless constructor No user-defined parameter-less constructor Destructors:
82
Class Struct Only reference destroyed immediately after scope is lost. Objects are removed by GC Destroyed immediately after scope is lost When copy, only get a copy of reference When copy, a new copy is created Can be sealed or not Implicitly sealed (no one can extend them)
83
C# Structs vs. C++ Structs (very different)
Same as C++ class, but all members are public User-defined value type Can be allocated on the heap, on the stack or as a member (can be used as value or reference) Always allocated on the stack or in-lined as a member field Members are always public Members can be public, internal or private
84
StructDemo struct StructDemo { private int id; private string name;
public int ID get {return this.id;} set { this.id = value; } } public string Name get { return this.name; } set { this.name = value; } public SimpleStruct(int id, string name) : this() this.ID = id; this.Name = name; public override string ToString() return "ID= " + ID + ", Name= " + Name;
85
Stack and Heap
86
Destructors (only in classes)*
A destructor in C# overrides System.Object.Finalize method. You have to use destructor syntax to do so. Manually overriding Finalize will give you an error message. Basically what you trying to do with your Finalize method declaration is hiding the method of the base class. It will cause the compiler to issue a warning which can be silenced using the new modifier (if it was going to work). The important thing to note here is that you can't both override and declare a new member with identical name at the same time so having both a destructor and a Finalize method will result in an error (but you can, although not recommended, declare a public new void Finalize() method if you're not declaring a destructor). ~Customer() { } No argument Constructor (only in classes)
87
Structure Syntax public struct StructureName { structure members... }
88
Example: Product as a structure
public struct Product { private string code; private string description; private decimal price; public Product(string code, string description, decimal price) this.code = code; this.description = description; this.price = price; } public string Code get return code; set code = value; * * * public string GetDisplayText(string sep) return Code + sep + Price.ToString("c") + sep + Description;
89
Quick Structures Summary
Can have all the same members as classes fields, properties, methods, events, static members, instance members No auto-implemented properties Unlike classes, no-argument constructor is always generated, even if the structure contains other constructors Unlike classes, if a structure contains a constructor with parameters, the constructor must initialize all structure’s instance variables.
90
Code that declares a variable as a structure type and assigns values to it
Create an instance of the Product structure (no need for new if uses default constructor, BUT values aren’t assigned to instance variables) Product p; Assign values to each instance variable p.Code = "CS15"; p.Description = "Murach's C# 2015"; p.Price = 56.50m; Call a method string msg = p.GetDisplayText("\n");
91
More about structures Product p = new Product();
Code that uses the default constructor to initialize the instance variables Product p = new Product(); Code that uses the constructor that accepts parameters to initialize the instance variables Product p = new Product("CS15", "Murach's C# 2015", 56.50m);
92
Assignments: Extra 12-1 Create and use an Inventory Item class
Add a class for an inventory item (InvItem) to the Inventory Maintenance application and then add the code that uses this class.
93
Project 3-1 Create a basic calculator*
94
Project 3-2 Assign tickets with time slots*
95
Project 3-2 Assign tickets with time slots (cont.)*
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.