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

C# Tutorial - An Object Oriented Approach to Programming

By David Bolton, About.com

7 of 10

Creating Objects and Variable Scope

Invoking a Constructor Constructors aren't called directly, but by using the keyword new - This has the syntax:
Class C = new C( ) ;
For instance this creates a new instance of class Simulation with the parameter 100.
Simulation CarSimulation = new Simulation( 100 ) ;

Scope and Destructors

One of the best things about .NET is that it does garbage collection for you. Unless you are using older unmanaged code, you do not have to worry about throwing away objects or memory leaks. C++ classes have a destructor and while it's possible to have one in C#, you rarely if ever need one. Probably nine out of ten C# developers will never have to write a destructor in their life. In a distant future tutorial I'll return to destructors but for now pretend I never mentioned them!

The Life of Variables

Variables, including objects exist as long as they are "in scope". If declared at the class level like topSpeed in RoadSegment then that variable exists until any instances of the class are no longer used. On the other hand, if declared local to a function, such as car in Simulation.RunSimulation() then car exists until the function is exited. There is also block scope, like the variable NewSpeed in Simulation.RunSimulation() ; This is created in the if block
if (Rnd.Next(...
within the do loop. It exists until the } just before the while statement. You can create variables within blocks within blocks etc. Variables in the outer block are visible in the inner block but not the other way round.
{
 int j=0;
  {
    int k = j+1; // This is ok
  }
 j=k; // Error - will not compile as k does not exist here any more
}

On the next page : The Car Sim Application and how it works

7 of 10

Explore C / C++ / C#

More from About.com

  1. Home
  2. Computing & Technology
  3. C / C++ / C#
  4. C# / C Sharp
  5. Learn C Sharp
  6. Creating Objects and Variable Scope

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

All rights reserved.