1. Home
  2. Computing & Technology
  3. C / C++ / C#

C# Tutorial - An Object Oriented Approach to Programming

By David Bolton, About.com

3 of 10

What's in a Class?

Lets have a look at the road segment class. Part of it is shown here.

    class RoadSegment
    {
        private int length=1000; // length in feet
        private int topSpeed = 30;
        private bool lastSegment = false;

    public int Length
    {
      get { return length; }
    }
}
This starts with a class definition- the word class followed by the class name just like in C++. This class has 3 fields all declared private. A field holds the data in the class- it''s just a variable.

Generally you should always make fields private so that nothing outside the class can alter them. You wouldn't want to touch the insides of a television- you could damage the TV (and yourself!) and in OOP, it's the same principle. Two of these fields are ints they hold integer values in the range -2,147,483,648 to 2,147,483,647. The third one is a bool which only has two values: false or true.

It is all too easy to declare public fields but this is a bad habit so please don't do it. But how then do you access the values from outside of the object if they are declared to be private? By declaring a property and using it. I've shown just the one property for Length but in the full listing I've also defined them for the other fields. This property is read only- you can't change it.

On the next page : How to use Properties

Explore C / C++ / C#
About.com Special Features

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

Easy ways to connect two computers for networking purposes. More >

  1. Home
  2. Computing & Technology
  3. C / C++ / C#
  4. C# / C Sharp
  5. Learn C Sharp
  6. What's in a Class?

©2009 About.com, a part of The New York Times Company.

All rights reserved.