C# Classes ISYS 512. Introduction to Classes A class is the blueprint for an object. –It describes...

Post on 14-Dec-2015

216 views 0 download

Transcript of C# Classes ISYS 512. Introduction to Classes A class is the blueprint for an object. –It describes...

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

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

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;

}

Using a Class

emp myEmp = new emp();myEmp.eid = "e1";myEmp.ename = "peter";myEmp.salary = 5000.00; MessageBox.Show(myEmp.empTax().ToString());

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.

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

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.

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

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

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

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.

Method Overloading Example

public double empTax()

{

return Salary * .1;

}

public double empTax(double sal)

{

return sal * .1;

}

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.

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

Inheritance Exampleclass emp

{

public string eid;

public string ename;

public double salary;

public double empTax()

{

return salary * .1;

}

}

class secretary : emp

{

public double wordsPerMinute;

}

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.

Database Handling Classes

Data SourceADO.NetObjects

DatabaseClasses

FormsReports

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.

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

}

public void getCustomerData(string searchCID) { string strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\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(); } }

public void SaveNewCustomer()

{

string strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\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();

}

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

Using the Customer Class to Add a New Customer

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

}

Other Methods

• Updating a record

• Deleting a record

Modeling 1:M Relation with Classes

• Employee– EID– Ename– Dependents

• Department– DID– Dname– Employees

• Customer– CID– Cname– Orders

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.

Implementing a 1:M Relationship With List

CIDCnameCityRatingOrders --- a List of orderMethods:

GetOrdersGetOrders

OIDOdateSalesPerson

Class Customer

Class Order

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

GetOrders Methodpublic void getOrders(string searchCID) { string strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\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); }

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

Binding Datagrid to a List

• dataGridView1.DataSource = myCust.orders;

Example

private void Form3_Load(object sender, EventArgs e) { string strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\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; } }

Assembly

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

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

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: Change the class to a public class ** very important

• Example: public class Customer

• 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

Using the Assembly

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

• Import the namespace.• using myCustomerService;

Code Using Assembly

Customer myCust = new Customer();myCust.CID = TextBox1.Text;myCust.getCustomerData(myCust.CID);TextBox2.Text = myCust.Cname;

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

Assembly that Returns DataSetpublic class GetDataSet { public DataSet getCustomerOrders() { string strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\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; } }

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:\\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); } } }

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

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.