How to create classes and objects in Visual C#

Article translations Article translations
Article ID: 307368 - View products that this article applies to.
This article was previously published under Q307368
For a Microsoft Visual Basic .NET version of this article, see 307210.
Expand all | Collapse all

On This Page

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.

Requirements

Prior knowledge required:
  • C# syntax
  • Object-oriented concepts

Create a new console application

  1. Start Visual Studio .NET or Visual Studio 2005, and create a new C# console application project named ClassesAndObjects.
  2. Save the project.

Create a new class

  1. From the Project menu, click Add Class.
  2. 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.
  3. Examine the code for the new class in the Code View window.

Define fields and constructors

  1. 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:
    http://msdn2.microsoft.com/en-us/library/t27ahy37.aspx
  2. 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;
  3. Repeat steps 1 and 2 (or type the code manually), to add another field as follows:
    private string stadium;
  4. Add two more fields, and provide initial field values as follows:
    private int wins = 0;
    private int defeats = 0;
  5. 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

  1. 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:
    http://msdn2.microsoft.com/en-us/library/t27ahy37.aspx
  2. 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)
    {
    
    }
  3. Define the body of the method as follows:
    public void PlayGame(int runsFor, int runsAgainst)
    {
       if (runsFor > runsAgainst)
          this.wins++;
       else
          this.defeats++;
    
    }
  4. 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.
  1. First, define an enum in the BaseballTeam class as follows:
    public enum Result {Win, Lose}
  2. 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

  1. 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:
    http://msdn2.microsoft.com/en-us/library/t27ahy37.aspx
  2. 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;
       }
    
    }
  3. 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;
       }
    
    }
  4. 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

  1. Display the code for Class1.cs in the Code View window.
  2. 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");
  3. Add the following code to test the public methods on the object:
    sf.PlayGame(7, 2);
    sf.PlayGame(BaseballTeam.Result.Lose);
  4. Add the following statements that exercise the properties of the object:
    Console.Out.WriteLine("Record: " + sf.Record);
    sf.Ballpark = "3Com Park";
  5. Display the current state of the object, as follows:
    Console.Out.WriteLine(sf.ToString());
  6. 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

  1. Build and run the application.
  2. Verify that the application displays the following information on the console:
    Record: 0.5
    San Francisco Giants, play at 3Com Park:  W1 L1

Properties

Article ID: 307368 - Last Review: December 11, 2006 - Revision: 3.3
APPLIES TO
  • Microsoft Visual C# 2005
  • Microsoft Visual C# .NET 2002 Standard Edition
Keywords: 
kbhowtomaster KB307368

Give Feedback

 

Contact us for more help

Contact us for more help
Connect with Answer Desk for expert help.
Get more support from smallbusiness.support.microsoft.com