1. Computing & Technology

Discuss in my forum

C# Tutorial - Getting Started

By , About.com Guide

8 of 8

A Quick Look at Classes
We'll cover numbers in more depth the next lesson or two- these are given to show examples of different types. Aa you would likely guess, you can't fit a big number into a smaller one so if you change the loop variable type from an int to a ulong like this:
 for (int a 
to
 for (ulong a 
then the compiler will complain about trying to initialize b with a as b is still an int. This is trying to stuff a 64 bit number into a 32 bit number. A quart into a pint does not go without losing a pint of whatever and the compiler will complain. You can get round this by forcing it with a cast but unless you really know why you have to use this (Just getting it to compile is not a good answer!), consider it a big hint that your code needs a rethink. The cast allows you to pour the quart into the pint, so that the compiler will compile it but you will still lose the top 32 bits of a!
 int b = (int)a; // a cast
 

Everything is Class Based

Unlike C++, variables can't exist at a global or file level, instead they exist only within classes. A class is a way of collecting different variables together and treating them as one entity. Think of a spaceship. It has weapons, crew, shields, velocity and location in 3 dimensions. In theory you could manage all this data without a class but what if you have a hundred spaceships? Then it gets a lot messier.

There are other benefits of using classes- these are known as encapsulation, inheritance and polymorphism. We'll look at these in more depth in a later lesson.

The next lesson will be about Object Oriented Programming in C#. This completes this tutorial.

©2012 About.com. All rights reserved.

A part of The New York Times Company.