46
C# Classes ISYS 512

C# Classes ISYS 512. Introduction to Classes A class is the blueprint for an object. It describes a particular type of object. It specifies the properties

Embed Size (px)

DESCRIPTION

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

Citation preview

Page 1: C# Classes ISYS 512. Introduction to Classes A class is the blueprint for an object. It describes a particular type of object. It specifies the properties

C# Classes

ISYS 512

Page 2: C# Classes ISYS 512. Introduction to Classes A class is the blueprint for an object. It describes a particular type of object. It specifies the properties

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.

Page 3: C# Classes ISYS 512. Introduction to Classes A class is the blueprint for an object. It describes a particular type of object. It specifies the properties

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

Page 4: C# Classes ISYS 512. Introduction to Classes A class is the blueprint for an object. It describes a particular type of object. It specifies the properties

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; }

Page 5: C# Classes ISYS 512. Introduction to Classes A class is the blueprint for an object. It describes a particular type of object. It specifies the properties

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());

Page 6: C# Classes ISYS 512. Introduction to Classes A class is the blueprint for an object. It describes a particular type of object. It specifies the properties

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.

Page 7: C# Classes ISYS 512. Introduction to Classes A class is the blueprint for an object. It describes a particular type of object. It specifies the properties

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; } }

Page 8: C# Classes ISYS 512. Introduction to Classes A class is the blueprint for an object. It describes a particular type of object. It specifies the properties

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.

Page 9: C# Classes ISYS 512. Introduction to Classes A class is the blueprint for an object. It describes a particular type of object. It specifies the properties

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

Page 10: C# Classes ISYS 512. Introduction to Classes A class is the blueprint for an object. It describes a particular type of object. It specifies the properties

Encapsulation

• 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.

Page 11: C# Classes ISYS 512. Introduction to Classes A class is the blueprint for an object. It describes a particular type of object. It specifies the properties

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; } } }

Page 12: C# Classes ISYS 512. Introduction to Classes A class is the blueprint for an object. It describes a particular type of object. It specifies the properties

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 yearsEmployedmyEmp2.DateHire = DateTime.Parse("7/4/2005");MessageBox.Show(myEmp2.yearsEmployed.ToString());

Page 13: C# Classes ISYS 512. Introduction to Classes A class is the blueprint for an object. It describes a particular type of object. It specifies the properties

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.

Page 14: C# Classes ISYS 512. Introduction to Classes A class is the blueprint for an object. It describes a particular type of object. It specifies the properties

Method Overloading Example

public double empTax()

{

return Salary * .1;

}

public double empTax(double sal)

{

return sal * .1;

}

Page 15: C# Classes ISYS 512. Introduction to Classes A class is the blueprint for an object. It describes a particular type of object. It specifies the properties

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.

Page 16: C# Classes ISYS 512. Introduction to Classes A class is the blueprint for an object. It describes a particular type of object. It specifies the properties

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

Page 17: C# Classes ISYS 512. Introduction to Classes A class is the blueprint for an object. It describes a particular type of object. It specifies the properties

Inheritance Exampleclass emp { public string eid; public string ename; public double salary; public double empTax() { return salary * .1; } } class secretary : emp { public double wordsPerMinute; }

Page 18: C# Classes ISYS 512. Introduction to Classes A class is the blueprint for an object. It describes a particular type of object. It specifies the properties

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()

Page 19: C# Classes ISYS 512. Introduction to Classes A class is the blueprint for an object. It describes a particular type of object. It specifies the properties

Database Handling Classes

Data SourceADO.NetObjects

DatabaseClasses

FormsReports

Page 20: C# Classes ISYS 512. Introduction to Classes A class is the blueprint for an object. It describes a particular type of object. It specifies the properties

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.

Page 21: C# Classes ISYS 512. Introduction to Classes A class is the blueprint for an object. It describes a particular type of object. It specifies the properties

Single-Record-Handling Class Exampleprivate 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; } }

Page 22: C# Classes ISYS 512. Introduction to Classes A class is the blueprint for an object. It describes a particular type of object. It specifies the properties

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(); } }

Page 23: C# Classes ISYS 512. Introduction to Classes A class is the blueprint for an object. It describes a particular type of object. It specifies the properties

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(); }

Page 24: C# Classes ISYS 512. Introduction to Classes A class is the blueprint for an object. It describes a particular type of object. It specifies the properties

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"); }

Page 25: C# Classes ISYS 512. Introduction to Classes A class is the blueprint for an object. It describes a particular type of object. It specifies the properties

Using the Customer Class to Add a New Customer

Page 26: C# Classes ISYS 512. Introduction to Classes A class is the blueprint for an object. It describes a particular type of object. It specifies the properties

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 = ""; }

Page 27: C# Classes ISYS 512. Introduction to Classes A class is the blueprint for an object. It describes a particular type of object. It specifies the properties

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

Page 28: C# Classes ISYS 512. Introduction to Classes A class is the blueprint for an object. It describes a particular type of object. It specifies the properties

Modeling 1:M Relation with Classes

• Employee– EID– Ename– Dependents

• Department– DID– Dname– Employees

• Customer– CID– Cname– Orders

Page 29: C# Classes ISYS 512. Introduction to Classes A class is the blueprint for an object. It describes a particular type of object. It specifies the properties

List<T> 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<T> represents a collection of T-class objects.

Page 30: C# Classes ISYS 512. Introduction to Classes A class is the blueprint for an object. It describes a particular type of object. It specifies the properties

Implementing a 1:M Relationship With List

CIDCnameCityRatingOrders --- a List of orderMethods:

GetOrdersGetOrders

OIDOdateSalesPerson

Class Customer

Class Order

Page 31: C# Classes ISYS 512. Introduction to Classes A class is the blueprint for an object. It describes a particular type of object. It specifies the properties

Customer Classprivate 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<Order> orders=new List<Order>();

Page 32: C# Classes ISYS 512. Introduction to Classes A class is the blueprint for an object. It describes a particular type of object. It specifies the properties

GetOrders Methodpublic 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); }

Page 33: C# Classes ISYS 512. Introduction to Classes A class is the blueprint for an object. It describes a particular type of object. It specifies the properties

Order Classclass 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;} }

Page 34: C# Classes ISYS 512. Introduction to Classes A class is the blueprint for an object. It describes a particular type of object. It specifies the properties

Binding Datagrid to a List

• dataGridView1.DataSource = myCust.orders;

Page 35: C# Classes ISYS 512. Introduction to Classes A class is the blueprint for an object. It describes a particular type of object. It specifies the properties

Example

Page 36: C# Classes ISYS 512. Introduction to Classes A class is the blueprint for an object. It describes a particular type of object. It specifies the properties

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; } }

Page 37: C# Classes ISYS 512. Introduction to Classes A class is the blueprint for an object. It describes a particular type of object. It specifies the properties

Assembly

• An assembly is a compiled code library used for deployment, versioning.

Page 38: C# Classes ISYS 512. Introduction to Classes A class is the blueprint for an object. It describes a particular type of object. It specifies the properties

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

Page 39: C# Classes ISYS 512. Introduction to Classes A class is the blueprint for an object. It describes a particular type of object. It specifies the properties

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

Page 40: C# Classes ISYS 512. Introduction to Classes A class is the blueprint for an object. It describes a particular type of object. It specifies the properties

Using the Assembly

• Reference the assembly: Project/Add Reference and use the Browse button to select the assembly.

• Import the namespace.• using myCustomerService;

Page 41: C# Classes ISYS 512. Introduction to Classes A class is the blueprint for an object. It describes a particular type of object. It specifies the properties

Code Using Assembly

Customer myCust = new Customer();myCust.CID = textBox1.Text;myCust.getCustomerData(myCust.CID);textBox2.Text = myCust.Cname;

Page 42: C# Classes ISYS 512. Introduction to Classes A class is the blueprint for an object. It describes a particular type of object. It specifies the properties

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"); }

Page 43: C# Classes ISYS 512. Introduction to Classes A class is the blueprint for an object. It describes a particular type of object. It specifies the properties

Assembly that Returns DataSetpublic 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; } }

Page 44: C# Classes ISYS 512. Introduction to Classes A class is the blueprint for an object. It describes a particular type of object. It specifies the properties

Class that Represents a Collection of All Customersclass AllCustomers { public List<Customer> CustomerList = new List<Customer>(); 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); } } }

Page 45: C# Classes ISYS 512. Introduction to Classes A class is the blueprint for an object. It describes a particular type of object. It specifies the properties

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

Page 46: C# Classes ISYS 512. Introduction to Classes A class is the blueprint for an object. It describes a particular type of object. It specifies the properties

ArrayList vs List<T>

• 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.