Home

Introduction to Classes

 

Introduction

Data types are usually referred to as primitive. Each of these data types is used to create an object that can hold a single value, such as the number of bedrooms of a house, the type of house, etc. Here are examples of such variables:

using System;

public class Exercise
{
    static int Main()
    {
        char TypeOfHome;
        int NumberOfBedrooms;
        byte Stories;
        double NumberOfBathrooms;
        int YearBuilt;
        double Value;

        return 0;
    }
}

Notice that, in this example, some or all of the variables could be used to create a single object.

Creating a Class

You can use one, or a group of more than one, type of values to create what would be referred to as a composite type. This type is created as a class. To create a class, start with either the struct or the class keyword, followed by a name, followed by an opening curly bracket "{" and a closing curly bracket "}". Everything between these brackets is part of the class and such a section is referred to as the body of the class. It would be created as follows:

struct House{ }

Or

class House{ }

In the body of the class, you can list the items that compose it. Each item is called a member of the class. Each item is identified by its type and a name. For example, if you want to create a House class that is simply known for its value, you can define a member value of double type. Such a class would look like this:

struct House{ double Value; }

Or

class House{ double Value; }

Most objects are made of various parts. Listing all parts on a single line could be cumbersome. Therefore, you can span the body of a class on various lines. An example would be:

struct House {
// Body of the class
}

or

struc House
{
// Body of the class
}

Or

class House {
// Body of the class
}

or

class House
{
// Body of the class
}

In the body of the class, you can then list its members. Each member is created as a variable, declaring it using any of the techniques we used in the previous lesson. Here are examples:
struct House
{
	char TypeOfHome;
	int NumberOfBedrooms;
	byte Stories;
	double NumberOfBathrooms;
	int YearBuilt;
	double Value;
}
class House
{
	char TypeOfHome;
	int NumberOfBedrooms;
	byte Stories;
	double NumberOfBathrooms;
	int YearBuilt;
	double Value;
}

If two variables are of the same type, you can declare them with one data type as done for variable declarations in the previous lesson. Here is an example:

struct House
{
    char TypeOfHome;
    int NumberOfBedrooms, YearBuilt;
    byte Stories;
    double NumberOfBathrooms, Value;
}
class House
{
    char TypeOfHome;
    int NumberOfBedrooms, YearBuilt;
    byte Stories;
    double NumberOfBathrooms, Value;
}
 

Home Copyright © 2006-2016, FunctionX, Inc. Next