Module 4: Creating Objects in C#
Overview
Defining a Class
Declaring Properties
Declaring Methods
Using Constructors
Using Static Class Members
Partial Types
Lesson: Defining a Class
What Are Classes and Objects?
What Are Value Types and Reference Types?
How to Define a Class and Create an Object
How to Organize Classes Using Namespaces
How to Define Accessibility and Scope
Multimedia: What Are Objects and Classes?
What Are Classes and Objects?
Classes: Are like blueprints for objects Contain methods and data
Class Class Covered Porch kitchen Dining Room
Living Room
Objects: Are instances of a class
Created using the new keyword Have actions
Object Object
Bath
Office
Family Room
What Are Value Types and Reference Types?
Value types
Reference types
Contain a reference to the data
Stored on the heap
Must be initialized
Declared using new keyword
Cannot be null
An int is a value type
.NET garbage collection handles destruction
A class is a reference type
Directly contain data
Stored on the stack
int int ii ==
i
i; i; 42; 42;
42 42
CostObject CostObject c; c;
c
••
42 42
How to Define a Class and Create an Object
How to define a class
public public class class Customer Customer {{ public name; public string string name; public public decimal decimal creditLimit; creditLimit; public customerID; public uint uint customerID; }}
How to instantiate a class as an object
Customer Customer nextCustomer nextCustomer == new new Customer(); Customer();
How to access class variables
nextCustomer.name nextCustomer.name == "Suzan "Suzan Fine"; Fine";
How to Organize Classes Using Namespaces
Declaring a namespace
namespace namespace CompanyName CompanyName {{ public public class class Customer Customer () () {{ }} }}
Nested namespaces
namespace namespace CompanyName CompanyName {{ namespace namespace Sales Sales {{ public public class class Customer Customer }} }} // // Or Or namespace namespace CompanyName.Sales CompanyName.Sales
The using statement
using using using using
System; System; CompanyName.Sales; CompanyName.Sales;
() () {{ }}
{{ ... ... }}
How to Define Accessibility and Scope ď Ž
Access modifiers are used to define the accessibility level of class members Declaration Declaration
Definition
public
Access not limited.
private
Access limited to the containing class.
internal
Access limited to this program.
protected protected internal
Access limited to the containing class and to types derived from the containing class Access limited to the containing class, derived classes, or to members of this program
Practice: Defining Classes and Creating Objects Hands-on Hands-on Practice Practice ď Žď Ž In this practice, you will define a class, In this practice, you will define a class,
instantiate instantiatean aninstance instanceof ofthe theclass, class,and and assign assignvalues valuesto tothe theclass classmembers members
10 min
Lesson: Declaring Properties ď Ž
How to Declare Properties
ď Ž
Using Properties
How to Declare Properties ď Ž
A Property has a set and a get functions
public public class class Course Course {{ private private string string courseNo; courseNo; private string courseName; private string courseName; private private double double credits; credits; public public string string CourseNo CourseNo {{ get get {{ return return courseNo; courseNo; }} set set {{ courseNo courseNo == value; value; }} }} public public string string CourseName CourseName {{ get get {{ return return courseName; courseName; }} set set {{ courseName courseName == value; value; }} }} }}
Using Properties
How to use Properties
Course Course oCourse oCourse == new new Course(); Course(); oCourse.CourseNo oCourse.CourseNo == “MA-101”; “MA-101”; oCourse.CourseName oCourse.CourseName == “Matemathics “Matemathics I” I” oCourse.Credits oCourse.Credits == 5; 5;
Practice: Using Properties Hands-on Hands-on Practice Practice
10 min
Lesson: Declaring Methods
How to Write a Method
How to Pass Parameters to a Method
How to Pass Parameters by Reference
How to Pass a Reference Type
How to Overload a Method
How to Use XML Code Comment Features
How to Write a Method ď Ž
A method is a command for action
class class Lion Lion {{ private private int int weight; weight; public public bool bool IsNormalWeight IsNormalWeight () () {{ if if ((weight ((weight << 100)||(weight 100)||(weight >> 250)) 250)) {{ return return false; false; }} return return true; true; }} public public void void Eat() Eat() {{ /* /* some some action action */ */ }} public public int int GetWeight() GetWeight() {return {return this.weight;} this.weight;} }} .. .. .. Lion Lion bigLion bigLion == new new Lion(); Lion(); bool bool weightNormal weightNormal == bigLion.IsNormalWeight(); bigLion.IsNormalWeight(); bigLion.Eat(); bigLion.Eat(); int int weight weight == bigLion.GetWeight(); bigLion.GetWeight();
How to Pass Parameters to a Method ď Ž
Passing by value
class class Lion Lion {{ private private int int weight; weight; public public void void SetWeight(int SetWeight(int newWeight) newWeight) {{ weight weight == newWeight; newWeight; }} }} .. .. .. Lion Lion bigLion bigLion == new new Lion(); Lion(); int int bigLionWeight bigLionWeight == 250; 250; bigLion.SetWeight( bigLion.SetWeight( bigLionWeight bigLionWeight ); );
How to Pass Parameters by Reference
Using the ref keyword
public public void void GetAddress(ref GetAddress(ref int int number, number, ref ref string string street) street) {{ number number == this.number; this.number; street street == this.street; this.street; }} .. .. .. int int sNumber sNumber == 0; 0; string string streetName streetName == null; null; zoo.GetAddress( zoo.GetAddress( ref ref sNumber, sNumber, ref ref streetName streetName ); ); // // sNumber sNumber and and streetName streetName have have new new values values
Definite assignment Using the out parameter keyword Allows you to initialize a variable in a method
How to Pass a Reference Type ď Ž
When you pass a reference type to a method, the method can alter the actual object
class class Zoo Zoo {{ public public void void AddLion( AddLion( newLion.location newLion.location .. .. .. }} }}
Lion Lion newLion newLion )) {{ == "Exhibit "Exhibit 3"; 3";
.. .. .. Zoo Zoo myZoo myZoo == new new Zoo(); Zoo(); Lion Lion babyLion babyLion == new new Lion(); Lion(); myZoo.AddLion( myZoo.AddLion( babyLion babyLion ); ); // // babyLion.location babyLion.location is is "Exhibit "Exhibit 3" 3"
How to Overload a Method ď Ž
Overloading enables you to create multiple methods within a class that have the same name but different signatures class class Zoo Zoo {{ public public void void {{ ... ... }} public public void void
}}
... ... }}
AddLion(Lion AddLion(Lion newLion) newLion) AddLion(Lion AddLion(Lion newLion, newLion, int int exhibitNumber) exhibitNumber) {{
How to Use XML Code Comment Features ď Ž
Three forward slashes (///) inserts XML comments
ď Ž
Hovering over a section of code produces a pop-up menu for accessing class member information
Practice: Writing and Calling a Method
Hands-on Hands-on Practice Practice
ď Žď Ž In this practice, you will add a method to In this practice, you will add a method to
an ananimal animalclass class
10 min
Lesson: Using Constructors
How to Initialize an Object
How to Overload a Constructor
How to Initialize an Object
Instance constructors are special methods that implement the actions required to initialize an object
Have the same name as the name of the class
Default constructor takes no parameters
public public class class Lion Lion {{ public public Lion() Lion() {{ Console.WriteLine("Constructing Console.WriteLine("Constructing Lion"); Lion"); }} }}
Readonly
Used to assign a value to a variable in the constructor
How to Overload a Constructor ď Ž
Create multiple constructors that have the same name but different signatures ď Ź
Specify an initializer with this
public public class class Lion Lion {{ private name; private string string name; private age; private int int age;
}}
public public Lion() Lion() :: this( this( "unknown", "unknown", 00 )) {{ Console.WriteLine("Default: Console.WriteLine("Default: {0}", {0}", name); name); }} public public Lion( Lion( string string theName, theName, int int theAge theAge )) {{ name name == theName; theName; age age == theAge; theAge; Console.WriteLine("Specified: Console.WriteLine("Specified: {0}", {0}", name); name); }}
Practice: Using Constructors
Hands-on Hands-on Practice Practice ď Žď Ž In this practice, you will modify the In this practice, you will modify the
solution solutionto tothe thelast lastpractice, practice,so sothat thatitit uses usesconstructors constructorsto toinitialize initializeanimal animal objects objectsproperly properly
10 min
Lesson: Using Static Class Members ď Ž
How to Use Static Class Members
ď Ž
How to Initialize a Class
How to Use Static Class Members
Static Members
Belong to the class
Initialize before an instance of the class is created
Shared by all instances of the class
class class Lion Lion {{ public public static static string string family family == "felidae"; "felidae"; }} ... ... // // AA Lion Lion object object is is not not created created in in this this code code Console.WriteLine( Console.WriteLine( "Family: "Family: {0}", {0}", Lion.family Lion.family ); );
How to Initialize a Class
Static Constructors
Will only ever be executed once
Run before the first object of that type is created
Have no parameters
Do not take an access modifier
May co-exist with a class constructor
Used to initialize a class
Practice: Using Static Class Members
Hands-on Hands-on Practice Practice
ď Žď Ž In this practice, you will modify a class to In this practice, you will modify a class to
use usestatic staticclass classmembers members
10 min
Lesson: Partial Types
How to Declare Partial Types
Using Partial Types
How to Declare Partial Types ď Ž
Partial classes allow you to split a class definition across multiple source files. The benefit of this approach is that it hides details of the class definition so that derived classes can focus on more significant portions.
public public partial partial class class Course Course {{ private private string string courseNo; courseNo; private private string string courseName; courseName;
}}
public public string string CourseNo CourseNo {{ ... ... }}
partial partial class class Course Course {{ public public void void Display() Display() {{ Console.WriteLine("Course Console.WriteLine("Course Information:"); Information:"); Console.WriteLine("\tCourse Console.WriteLine("\tCourse No.: No.: "+this.CourseNo); "+this.CourseNo); Console.WriteLine("\tCourse Console.WriteLine("\tCourse Name: Name: "+this.CourseName); "+this.CourseName); }} }}
How to Use Partial Types
Course Course oCourse oCourse == new new Course(); Course(); oCourse.CourseNo oCourse.CourseNo == “MA-101”; “MA-101”; oCourse.CourseName oCourse.CourseName == “Matemathics “Matemathics I” I” oCourse.Credits oCourse.Credits == 5; 5; oCouse.Display(); oCouse.Display();
Review
Defining a Class
Declaring Methods
Using Constructors
Using Static Class Members