Download presentation
Presentation is loading. Please wait.
Published byClarence Terry Modified over 9 years ago
1
C# Classes ISYS 512
2
Introduction to Classes A class is the blueprint for an object. –It describes a particular type of object. –It specifies the properties (fields) and methods a particular type of object can have. –One or more object can be created from the class. –Each object created from a class is called an instance of the class.
3
Adding a Class to a Project Project/Add Class –Assigna meaningful name. Steps: –Adding properties Property procedures: Set / Get Or declare Public variables –Adding methods –Adding events, exceptions
4
Class Code Example: Properties defined using Public variables class emp { public string eid; public string ename; public double salary; public double empTax() { return salary *.1; }
5
Using a Class: Creating an instance of the class using new emp myEmp = new emp(); myEmp.eid = "e1"; myEmp.ename = "peter"; myEmp.salary = 5000.00; MessageBox.Show(myEmp.empTax().ToString());
6
Creating Property with Property Procedures Implementing a property with a public variable the property value cannot be validated by the class. We can create read-only, write-only, or write-once properties with property procedure. Steps: –Declaring a private class variable to hold the property value. –Writing a property procedure to provide the interface to the property value.
7
class emp2 { private string pvEID; private string pvEname; private double pvSalary; public string EID { get { return pvEID; } set { pvEID = value; } public string Ename { get {return pvEname;} set {pvEname = value;} } public double Salary { get {return pvSalary;} set {pvSalary = value;} } public double empTax() { return Salary *.1; }
8
How the Property Procedure Works? When the program sets the property, the set property procedure is called and procedure code is executed. The value assigned to the property is passed in the value variable and is assigned to the hidden private variable. When the program reads the property, the get property procedure is called.
9
Anatomy of a Class Module Class Module Public Variables & Property Procedures Public Procedures & Functions Exposed Part Private Variables Private Procedures & Functions Hidden Part Private variables and procedures can be created for internal use. Encapsulation
10
Encapsulation is to hide the variables or something inside a class, preventing unauthorized parties to use. So methods like getter and setter access it and the other classes access it through property procedure.
11
Property Procedure Code Example: Enforcing a maximum value for salary public double Salary { get {return pvSalary;} set { if (value > 150000) { pvSalary = 150000; } else { pvSalary = value; }
12
Implementing a Read-Only Property: Declare the property with only the get procedure public DateTime DateHire { get { return pvDateHire; } set { pvDateHire = value; } } public int yearsEmployed { get { return DateTime.Today.Year - DateHire.Year; } Using the property: cannot assign a value to yearsEmployed myEmp2.DateHire = DateTime.Parse("7/4/2005"); MessageBox.Show(myEmp2.yearsEmployed.ToString());
13
Overloading A class may have more than one methods with the same name but a different argument list (with a different number of parameters or with parameters of different data type), different parameter signature.
14
Method Overloading Example public double empTax() { return Salary *.1; } public double empTax(double sal) { return sal *.1; }
15
Inheritance The process in which a new class can be based on an existing class, and will inherit that class’s interface and behaviors. The original class is known as the base class, super class, or parent class. The inherited class is called a subclass, a derived class, or a child class.
16
Employee Super Class with Three SubClasses All employee subtypes will have emp nbr, name, address, and date-hired Each employee subtype will also have its own attributes
17
Inheritance Example class emp { public string eid; public string ename; public double salary; public double empTax() { return salary *.1; } class secretary : emp { public double wordsPerMinute; }
18
Method Override class emp { public string eid; public string ename; public double salary; public virtual double empTax() { return salary *.1; } class secretary : emp { public double wordsPerMinute; public override double empTax() { return salary *.15; } Note: The keyword virtual allows a parent class method to be overridden. Example: public virtual double empTax()
19
Database Handling Classes Data Source ADO.Net Objects Database Classes Forms Reports
20
Single-Record-Handling Classes –Retrieves a single record from the database and makes it available to your application in the form of an object. –The fields in the record are exposed as the object’s properties. –Any actions performed by the data (updates, calculations, etc.) are exposed as the object’s methods.
21
Single-Record-Handling Class Example private string pvCID; private string pvCname; private string pvCity; private string pvRating; private Boolean pvRecExist; public string CID { get { return pvCID; } set { pvCID = value; } } public string Cname { get { return pvCname; } set { pvCname = value; } } public string City { get { return pvCity; } set { pvCity = value; } } public string Rating { get { return pvRating; } set { pvRating = value; } } public Boolean RecExist { get { return pvRecExist; } }
22
public void getCustomerData(string searchCID) { string strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\CSharpexamples\\SalesDB2011.accdb"; OleDbConnection objConn = new OleDbConnection(strConn); string strSQL = "select * from customer where cid='" + searchCID + "'"; OleDbCommand objComm = new OleDbCommand(strSQL, objConn); objConn.Open(); OleDbDataReader objDataReader; objDataReader = objComm.ExecuteReader(); if (objDataReader.Read() == false) { pvRecExist = false; } else { pvRecExist = true; CID = objDataReader["CID"].ToString(); Cname=objDataReader["Cname"].ToString(); City = objDataReader["City"].ToString(); Rating = objDataReader["Rating"].ToString(); }
23
public void SaveNewCustomer() { string strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\CSharpexamples\\SalesDB2011.accdb"; OleDbConnection objConn = new OleDbConnection(strConn); string strSQLInsert; strSQLInsert = "Insert into Customer values ('"; strSQLInsert += CID + "','" + Cname + "','"; strSQLInsert += City + "','" + Rating + "')"; OleDbCommand objCommInsert = new OleDbCommand(strSQLInsert, objConn); objConn.Open(); objCommInsert.ExecuteNonQuery(); objConn.Close(); }
24
Using the Customer Class private void button1_Click(object sender, EventArgs e) { Customer myCust = new Customer(); myCust.CID = textBox1.Text; myCust.getCustomerData(myCust.CID); if (myCust.RecExist) { textBox2.Text = myCust.Cname; textBox3.Text = myCust.Rating; } else MessageBox.Show("record not exist"); }
25
Using the Customer Class to Add a New Customer
26
Using the SaveNewCustomer Method to Add A New Customer private void button1_Click(object sender, EventArgs e) { Customer newCust = new Customer(); newCust.CID = textBox1.Text; newCust.Cname = textBox2.Text; newCust.City = textBox3.Text; newCust.Rating = textBox4.Text; newCust.SaveNewCustomer(); textBox1.Text = ""; textBox2.Text = ""; textBox3.Text = ""; textBox4.Text = ""; }
27
Other Methods Updating a record Deleting a record Note: CRUD –Create or add new entries – Read, retrieve, search, or view existing entries – Update or edit existing entries – Delete/deactivate existing entries
28
Modeling 1:M Relation with Classes Employee –EID –Ename –Dependents Department –DID –Dname –Employees Customer –CID –Cname –Orders
29
List Class Represents a strongly typed list of objects that can be accessed by index where T is the type of elements in the list. T can be an entity class so that List represents a collection of T-class objects.
30
Implementing a 1:M Relationship With List CID Cname City Rating Orders --- a List of order Methods: GetOrders OID Odate SalesPerson Class Customer Class Order
31
Customer Class private string pvCID; private string pvCname; private string pvCity; private string pvRating; private Boolean pvRecExist; public string CID { get { return pvCID; } set { pvCID = value; } } public string Cname { get { return pvCname; } set { pvCname = value; } } public string City { get { return pvCity; } set { pvCity = value; } } public string Rating { get { return pvRating; } set { pvRating = value; } } public Boolean RecExist { get { return pvRecExist; } } public List orders=new List ();
32
GetOrders Method public void getOrders(string searchCID) { string strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\CSharpexamples\\SalesDB2011.accdb"; OleDbConnection objConn = new OleDbConnection(strConn); string strSQL = "select * from orders where cid='" + searchCID + "'"; OleDbCommand objComm = new OleDbCommand(strSQL, objConn); objConn.Open(); OleDbDataReader objDataReader; objDataReader = objComm.ExecuteReader(); while (objDataReader.Read() == true) { Order ord = new Order(); ord.OID = objDataReader["oid"].ToString(); ord.CID = objDataReader["cid"].ToString(); ord.Odate = (DateTime)objDataReader["odate"]; ord.SalesPerson = objDataReader["salesPerson"].ToString(); orders.Add(ord); }
33
Order Class class Order { private string pvOID; private string pvCID; private DateTime pvOdate; private string pvSalesPerson; public string OID { get {return pvOID;} set {pvOID=value;} } public string CID { get {return pvCID;} set {pvCID=value;} } public DateTime Odate { get {return pvOdate;} set {pvOdate=value;} } public string SalesPerson { get {return pvSalesPerson;} set {pvSalesPerson=value;} }
34
Binding Datagrid to a List dataGridView1.DataSource = myCust.orders;
35
Example
36
private void Form3_Load(object sender, EventArgs e) { string strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\CSharpexamples\\SalesDB2011.accdb"; OleDbConnection objConn = new OleDbConnection(strConn); string strSQL = "select CID from customer;"; OleDbCommand objComm = new OleDbCommand(strSQL, objConn); objConn.Open(); OleDbDataReader objDataReader; objDataReader = objComm.ExecuteReader(); while (objDataReader.Read() == true) { listBox1.Items.Add(objDataReader["CID"]); } private void listBox1_SelectedIndexChanged(object sender, EventArgs e) { Customer myCust = new Customer(); myCust.getCustomerData(listBox1.SelectedItem.ToString()); if (myCust.RecExist) { textBox1.Text = myCust.Cname; textBox2.Text = myCust.Rating; myCust.getOrders(myCust.CID); dataGridView1.DataSource = myCust.orders; }
37
Assembly An assembly is a compiled code library used for deployment, versioning.
38
Difference between Assembly and Class A class defined in a project is available to that project only. Once a class is compiled in an assembly it can be used by any projects. To create an assembly: –Start a Class Library project
39
Steps to Create An Assembly Start a Class Library project Create classes –You can also use existing classes defined in other projects by Project/Add Existing Item Note 1: Change the class to a public class ** very important Example: public class Customer Note 2: You may need to rename the namespace Save project Select Build/Build to compile the code. –When the class library is compiled successfully, an assembly is created and stored in the project’s Bin/Debug folder. –Example: A testClassLib project is created in C:\CSharpExamples, then the assembly is found in: –C:\CSharpExamples\testClassLib\testClassLib\bin\Debug
40
Using the Assembly Reference the assembly: Project/Add Reference and use the Browse button to select the assembly. Import the namespace. using myCustomerService;
41
Code Using Assembly Customer myCust = new Customer(); myCust.CID = textBox1.Text; myCust.getCustomerData(myCust.CID); textBox2.Text = myCust.Cname;
42
Assembly with Customer and Order classes private void button1_Click(object sender, EventArgs e) { Customer myCust = new Customer(); myCust.CID = textBox1.Text; myCust.getCustomerData(myCust.CID); if (myCust.RecExist) { textBox2.Text = myCust.Cname; myCust.getOrders(myCust.CID); dataGridView1.DataSource = myCust.orders; } else MessageBox.Show("record not exist"); }
43
Assembly that Returns DataSet public class GetDataSet { public DataSet getCustomerOrders() { string strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\CSharpexamples\\SalesDB2011.accdb"; OleDbConnection objConn = new OleDbConnection(strConn); string strSQL = "select * from customer;"; OleDbDataAdapter objAdapter = new OleDbDataAdapter(strSQL, objConn); DataSet objDataSet = new DataSet(); objAdapter.Fill(objDataSet, "Customer"); string strSQL2 = "select * from orders;"; objAdapter.SelectCommand.CommandText = strSQL2; objAdapter.Fill(objDataSet, "orders"); return objDataSet; }
44
Class that Represents a Collection of All Customers class AllCustomers { public List CustomerList = new List (); public void getAllCustomers() { string strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\CSharpexamples\\SalesDB2011.accdb"; OleDbConnection objConn = new OleDbConnection(strConn); string strSQL = "select * from customer"; OleDbCommand objComm = new OleDbCommand(strSQL, objConn); objConn.Open(); OleDbDataReader objDataReader; objDataReader = objComm.ExecuteReader(); while (objDataReader.Read()==true) { Customer cust = new Customer(); cust.CID = objDataReader["CID"].ToString(); cust.Cname = objDataReader["Cname"].ToString(); cust.City = objDataReader["City"].ToString(); cust.Rating = objDataReader["Rating"].ToString(); CustomerList.Add(cust); }
45
Changes to Assembly Old projects referencing the assembly will get the latest version of the assembly. Compatible changes: –Changes to assembly that will not break the older projects. –Examples: Adding a property, adding a method Incompatible changes –Changes to assembly that will break the older projects. –Examples: Deleting or renaming a property or a method
46
ArrayList vs List ArrayList is a data structure used to store a set of values. –Its capacity is automatically expanded as needed. –Values stored in an arraylist do not have to be the same data type. –Flexibility when inserting/deleting elements.
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.