How to create classes and objects in Visual C# (307368)
The information in this article applies to:
- Microsoft Visual C# 2005
- Microsoft Visual C# .NET (2002)
This article was previously published under Q307368
For a Microsoft Visual Basic .NET version of this article, see 307210.
SUMMARY
This step-by-step article shows you how to create a new class in C# to represent a baseball team. You will define fields, methods, and properties for the class. You will then create an object of this class type and make use of its methods and properties.
C# is an object-oriented programming language. You define classes to represent the types in your application, and then you create objects as instances of these classes. A class can contain fields, methods, properties, and indexers. RequirementsPrior knowledge required:- C# syntax
- Object-oriented concepts
Create a new console application- Start Visual Studio .NET or Visual Studio 2005, and create a new C# console application project named ClassesAndObjects.
- Save the project.
Create a new class- From the Project menu, click Add Class.
- In the Add New Item dialog box, for Class name type BaseballTeam, and then click Open.
Note In Visual C# 2005, Open is changed to Add. - Examine the code for the new class in the Code View window.
Define fields and constructors- From the View menu, click Class View. In the Class View window, expand the ClassesAndObjects project, and then expand the ClassesAndObjects namespace. Right-click the BaseballTeam class, choose Add, and then click Add Field.
Note Visual C# 2005 has some design changes. For more information, visit the following Microsoft Web site: - In the C# Field Wizard, set the Field access to private and set the Field type to string. For Field name, type name. Click Finish. This adds the following field to the class:
private string name; - Repeat steps 1 and 2 (or type the code manually), to add another field as follows:
private string stadium; - Add two more fields, and provide initial field values as follows:
private int wins = 0;
private int defeats = 0; - Modify the constructor for the class to initialize the name of the team and the stadium:
public BaseballTeam(string n, string s)
{
this.name = n;
this.stadium = s;
}
Define methods- In the Class View, right-click the BaseballTeam class. Choose Add, and then click Add Method.
Note Visual C# 2005 has some design changes. For more information, visit the following Microsoft Web site: - Set the Method access to public and set the Return type to void. For the Method name type PlayGame. Add two int parameters named runsFor and runsAgainst. Click Finish. This adds the following method to the class:
public void PlayGame(int runsFor, int runsAgainst)
{
} - Define the body of the method as follows:
public void PlayGame(int runsFor, int runsAgainst)
{
if (runsFor > runsAgainst)
this.wins++;
else
this.defeats++;
} - All classes in C# ultimately inherit from a base class called Object. This class defines common capabilities for all classes. An example is the ToString method, which returns a string representation of the class state. Override this method in your BaseballTeam class as follows:
public override string ToString()
{
return this.name + ", play at " + this.stadium + ": " +
" W" + this.wins + " L" + this.defeats;
}
Define overloaded methods
C# supports overloaded methods, which are methods that have the same name but a different signature. In step 2 below, you will define an overloaded version of the PlayGame method that takes the result of a game as its parameter.
- First, define an enum in the BaseballTeam class as follows:
public enum Result {Win, Lose} - Create another PlayGame method as follows:
public void PlayGame(Result r)
{
if (r == Result.Win)
this.wins++;
else if (r == Result.Lose)
this.defeats++;
}
Define properties- In the Class View, right-click the BaseballTeam class. Choose Add, and then click Add Property.
Note Visual C# 2005 has some design changes. For more information, visit the following Microsoft Web site: - Set the Property access to public and set the Property type to double. For the Property name type Record. Click the get radio button, and then click Finish. This adds the following property to the class:
public double Record
{
get
{
return 0;
}
} - Modify the property as follows, so that it returns the baseball team's playing record (for example, if the team wins 10 games and loses 10 games, its record is 0.5):
public double Record
{
get
{
int played = this.wins + this.defeats;
return (double)this.wins / played;
}
} - Add a get/set property named Ballpark as follows. This property allows the baseball team's stadium field to be read or changed:
public string Ballpark
{
get
{
return this.stadium;
}
set
{
this.stadium = value; // value is an implicit parameter
}
}
Create and use an object- Display the code for Class1.cs in the Code View window.
- In the Main method, create a BaseballTeam object by using the new operator. Assign the object reference to a local BaseballTeam variable as follows:
BaseballTeam sf = new BaseballTeam("San Francisco Giants",
"Candlestick Park"); - Add the following code to test the public methods on the object:
sf.PlayGame(7, 2);
sf.PlayGame(BaseballTeam.Result.Lose); - Add the following statements that exercise the properties of the object:
Console.Out.WriteLine("Record: " + sf.Record);
sf.Ballpark = "3Com Park"; - Display the current state of the object, as follows:
Console.Out.WriteLine(sf.ToString()); - Set the object reference to null to indicate that you no longer need the BaseballTeam object. This makes the object available for garbage collection (note that C# does not have a delete operator):
sf = null;
Verify that it works- Build and run the application.
- Verify that the application displays the following information on the console:
Record: 0.5
San Francisco Giants, play at 3Com Park: W1 L1
Modification Type: | Minor | Last Reviewed: | 10/4/2006 |
---|
Keywords: | kbHOWTOmaster KB307368 kbAudDeveloper |
---|
|