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

C# Tutorial - An Object Oriented Approach to Programming

By , About.com Guide

6 of 10

About Object Methods and Constructors

Methods

In a class, code is organised into methods also known as functions- these are blocks of code that do something like:
car.Travel() ;
Methods can return a value and the way to distinguish a method from a property is that a property does not have brackets and a method does. A property is an attribute of the object while a method does something and should have meaningful names E.G. FetchData(), DoLogin(), calculateTotal() etc.

car.Travel() ; // calling a method
int carspeed = car.Speed;// Property being used
Methods can be public or private. There are other access modifiers as well and in next C# tutorial, we'll look at them in greater depth.

Constructing a Class

Below is the constructor for the RoadSegment class.
    public RoadSegment(int _length, bool _lastSegment, int _topSpeed)
    {
        length = _length;
        lastSegment = _lastSegment;
        topSpeed = _topSpeed;
    }
A constructor is an optional method with the same name as the class itself. Every class has a constructor, even if you don't define one the compiler will generate one for you without any parameters. When the constructor code starts, all fields have already been initialized to their default values. This is 0 for numeric types, empty string "" for strings and null for objects unless initial values are provided.

In RoadSegment though each field starts off with a default value, when the constructor is called, it initializes the fields with new values from the passed parameters. I prefixed each parameter with an underscore to distinguish it from the field name.

on the next page :

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

Holiday Central

What to eat, where to go, fun things to do and how to save money on the perfect gifts. More >

Family Tech Center

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

  1. Home
  2. Computing & Technology
  3. C / C++ / C#
  4. C# / C Sharp
  5. Learn C Sharp
  6. About Object Methods and Constructors

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

All rights reserved.