Classes Fundamentals

Introduction

To use a variable, we can declare it using either var keyword or a known and simple data type. For example, we can use an integer to declare a variable that represented the number of bedrooms of a house. Here is an example:

class Program
{
    static void Main()
    {
        int bedrooms = 3;
    }
}
Class

As opposed to a simple variable, in C#, you can use one or more variables to create a more complete or complex object.

A class is a technique of using one or a group of variables to be used as a foundation for a more detailed variable.

Practical LearningPractical Learning: Introducing Classes

  1. Start Microsoft Visual Studio
  2. To create a new application, on the main menu, click File -> New -> Project
  3. In the middle list, click Empty Project
  4. Change the Name to DepartmentStore1
  5. Click OK

Classes and Files

One way you can organize the classes of your application is to put them in different files. A file can contain as many classes as necessary.

Classes's Files and Folders

One way you can organize files is to put them in different folders. This also applies to files that contain classes.

Introduction to Creating a Class

A class is created in a file. A file that contains (a) class(es) is a regular text-based file that has the extension .cs. A file can contain one or more classes. A class starts with a keyword named class.

To create a new class:

Any of these actions would display the Add New Item dialog box with the Class option selected. If you had selected the Add New Item from the main menu or the Solution Explorer, you can click Class. In the Name text box, accept or change the default name and click Add. A new file named after the class with the .cs extension would be added to your project.

You can also use skeleton code to start a class:

A class with the default name MyClass would be added. You can accept that name or change it.

Manually Creating a Class

There are various ways you can create a class. If you are working from a text editor, start a file, type class.

Naming a Class

Like a variable, a class must have a name. The name follows the class keyword. The name primarily follows the same rules as the variables. You can then add your own rules. In our lessons:

The Body of a Class

To present its description, a class has members. The list of the members of a class is specified after the name of the class. The members are included between an opening curly bracket { and a closing curly bracket }. The section between the curcly brackets is referred to as the body of the class. It would appear as follows:

class House { . . . }

As mentioned above, the members of a class are included inside its curly brackets. Here is an example:

class House { string typeOfHouse; int numberOfBedrooms; double price; }

Although this code is legal, to make it easier to read, you can include each curcly bracket on its own line and each member on its own line, like this:

class House {
    string typeOfHouse;
    int numberOfBedrooms;
    double price; }

Or this:

class House
{
    string typeOfHouse;
    int numberOfBedrooms;
    double price;
}

As mentioned earlier, the variables that are the same type can be declared together using their common type. Here are examples:

class State
{
    string capital;
    string abbrev, name, dateOfAdmissionToUnion;
    int orderOfAdmissionToUnion;
    double areaInSquareMiles, areaInKilometers;
}

Practical LearningPractical Learning: Creating a Class

  1. To create a class, In the Solution Explorer, right-click DepartmentStore1. Position the mouse on Add, and click New Item...
  2. In the Add New Item dialog box, in the left list, under Visual C#, click Code
  3. In the middle list, click Code File
  4. Change the Name to StoreItem
  5. Click Add
  6. Type the code as follows:
    class StoreItem
    {
    
    }

Managing Classes

Introduction

Microsoft Visual Studio provides many tools and visual objects used to manage classes of an application. The studio makes it possible to conveniently rename a class (or one of its members) or to easily navigate to a class.

The Class View

Probably the best window to manage classes is called the Class View. To get the Class View:

The Class View is made of six sections. The title bar and the use of the Class View follow the same description as for the Solution Explorer:

Class View

The second part of the title bar is its toolbar Toolbar.

The Class View New Folder button allows you to create and add a new folder to the project. The Back and the Forward buttons allow you to navigate among the classes.

Under the toolbar, there is another bar made of a combo box and a button. These allow you to search.

The body of the Class View is made of two sections. The first node of the upper section displays the name of the project. Under the project node, the names of classes display. The bottom section of the Class View is used to display the members of a class. To see the members of a class, you can click it in the top window. Here is an example:

Class View

The Class View provides another way to create a class. To do this, right-click the name of the project, position the mouse on Add, and click Class...

Practical LearningPractical Learning: Introducing Classes

  1. On the main menu, click Project -> Add New Item...
  2. In the middle list of the Add New Item dialog box, click Code File
  3. Change the name to StoreItem 
    New Project
  4. Click Add
  5. In the file, type the following:
    class StoreItem
    {
    }
  6. On the main menu, click View -> Solution Explorer
  7. To create another code file, in the Solution Explorer, right-click DepartmentStore1, position the mouse on Add and click New Item...
  8. In the middle list of the Add New Item dialog box, click Code File
  9. Change the name to DepartmentStore
  10. Click Add
  11. In the empty document, type the following:
    class DepartmentStore
    {
        static void Main()
        {
        }
    }

Accessing a Class

As mentioned already, you can create as many classes as you want for your project. You can create each class in its own file or you can create many classes in the same file. After creating them, to access a class:

Renaming a Class

If you don't like the name a class is using, you can change it. The primary technique consists of locating it in your text editor or the Code Editor and edit its name. If you use that approach, you will also have to find every section where the name of the class is used. This can be cumbersome and lead to mistakes. If you are working from either Microsoft Visual Studio, it provides a better solution and would take care of everything behind the scenes.

To rename a class in Microsoft Visual C# or Microsoft Visual Studio:

Any of these actions would display the Rename dialog box. In the New Name text box, type the desired name or edit it. Use the check boxes to indicate whether you want the Code Editor to change the name, if used, in the comment and the strings. When you are ready, click OK. This would display the Preview Changes - Rename dialog box that shows the various parts where the name is used. When you have checked everything, if it suits you, click Apply.

C# Language Accessories

Unsafe Code

When C# was invented, one of its biggest goals was to avoid some of the difficulties of C/C++. Among them was the use of pointers. C/C++ uses pointers to refer to the area in memory where a value is located. C# highly avoids pointers and takes over memory management as opposed to letting the programmer take care of that aspect of an application. You can still use pointers in C# in extreme cases when you judge them necessary.

Because the C# compiler is in charge of managing the memory used by the values of an application, pointers are said to be unsafe. If you want to use a pointer in your application, you must precede the name of every method that uses unsafe code with the unsafe keyword. Here is an example:

class Exercise
{
	unsafe static void Main()
	{
		int Length = 224;
		int *Len = &Length;
		
		System.Console.Write("Length ");
		System.Console.WriteLine(Length);
		System.Console.Write("Length ");
		System.Console.WriteLine(*Len);
		System.Console.WriteLine();

		Length = 804;
		System.Console.Write("Length ");
		System.Console.WriteLine(Length);
		System.Console.Write("Length ");
		System.Console.WriteLine(*Len);
	}
}

To compile the application, you must indicate that you are using unsafe code. To do that, use the /unsafe modifier.

To apply this option in Microsoft Visual Studio, on the main menu, you can click Project -> Project Properties... In the Build section, click the Allow Unsafe Code check box:

Unsafe Code

Region Delimiters

Microsoft Visual Studio provides various techniques to assist you with code writing and management. The characteristics include color-coded words, intuitive indentation, the IntelliSense, delimitation of sections of code, etc. Consider the following contents of the Code Editor based on what we have reviewed so far:

Code Editor

Notice that there are - buttons on the left side of some lines of code. These allow you to collapse a section of code if you think you don't need to see it. To do this, you can click the - button. If you click that - button, it changes into a + button. Here is an example:

Code Editor

The + button allows you to expand a hidden code section. This behavior of creating + and - buttons is part of the Code Editor of Microsoft Visual Studio (yes, many other programming environments use that behavior also). To create these sections, the Code Editor follows some rules. For example, it looks for the start and end of such an item as a  classes (or other items we will study in other lessons).

Besides, or instead of, the sections of code created by the Code Editor, if you want, you can create your own sections. To create a section:

When and where you start a region, the #region expression is required. On the right side of this expression, you can type anything you want on the line. To end the section, type #endregion, followed by anything you want. Consider the following example:

class Circle
{
}

#region This section is reserved for quadrilateral shapes
class Rectangle
{
}

class Square
{
}
#endregion This is the end of the quadrilateral section

class Line
{
}

You don't have to type anything on the right side of #endregion. After creating the region, the Code Editor would display a - button to the left side of #region with a line from there to the left of #endregion:

Regions in the Code Editor

This then allows you to expand and collapse that section at will:

Regions in the Code Editor

We mentioned that you didn't have to type anything on the right side of #endregion and you could leave it empty. In our example, notice that there is a rectangle with gray lines around the string that follows #region. This rectangle doesn't cover the string that follows #endregion. This means that if you don't type anything on the right side of #endregion, that section on the right side the #region line would not show.

Introduction to Using a Class

Creating an Object

Like any normal variable, to use a class in your program, you can first declare a variable for it. Declaring a variable of a class is also referred to as creating an object or creating an instance of a class.

Like the variables we introduced in Lessons 3 and 4, to declare a variable of a class, you can use the var keyword. Alternatively, you can type its name followed by a name for the variable. For example, to declare a variable of the above House class, you could type the following:

class House
{
}

class Program
{
    static void Main()
    {
        var property . . .
    }
}

Or the following:

class House
{
}

class Program
{
    static void Main()
    {
        House property;
    }
}

Value Types and Reference Types

In Lessons 3 and 4, we saw how to declare variables of regular types. We also mentioned that, when such variables are initialized, the compiler stores their values in the memory area it had previously reserved. The data types used for such variables are called value types. To store their values, the compiler creates a memory area named a stack. The other area is named the heap. This is reserved for variables declared for classes.

When you declare a variable using a class, you must ask the compiler to allocate memory for it, on the heap. To make this request, you use an operator called new. Here is an example:

class House
{
}

class Program
{
    static void Main()
    {
        var property = new House();
    }
}

Instead of the var keyword, you can declare the variable using the name of the class. As mentioned for value types, if you use the var keyword, you must allocate memory immediately. If you use the name of the class, you can declare the variable on one line, then use the new operator on another line to allocate memory for it. Here is an example:

class House
{
}

class Program
{
    static void Main()
    {
        House property;
        
	// You can do something here

        property = new House();
    }
}

In C#, as well as Visual Basic, if you create a class in any of the files that belong to the same project, the class is made available to all other files of the same project.

Practical LearningPractical Learning: Declaring a Variable of a Class Type

A Null Object

When you need to use the values and behaviors that a class offers, we saw that you must declare a variable for it. This allows the compiler to fill the memory reserved for that variable with the desired value(s). Sometimes, when declaring the variable, you may not be ready to provide the necessary values for the variable.

A variable that has been declared for a class but that has not yet received (a) value(s) in referred to as a null object. To create a null object, when declaring the variable, use the name of the class, followed by a name for the variable, and assign the null keyword to it.

In our introduction to primitive data types, we saw that, to indicate that a variable cab hold a null value, you can add a question mark to it. If you are using a class, don't add a question mark to the name of the class. Here is an example:

class House
{
}

class Program
{
    static void Main()
    {
        House property = null;
    }
}

If a variable of a class was previously declared and initialized but, one way or another, the values have been removed or deleted, the variable is also referred to as a null object. Most of the times, you will only be interested to find out whether an object is null.

Sharing a Class

C# code can complement code from other languages such as C++/CLI, Visual Basic, and F#. In other words, code from these other languages should be able to "read" or access code written in a C# application. To make this possible, a C# class can be created as a public object.

If you want your class to be accessible to code written in other languages, precede the class keyword with public when creating it. Here is an example:

public class Exercise
{
    static void Main()
    {
	var number = 244;
	var thing  = "Vehicle";

	System.Console.WriteLine(number);
	System.Console.WriteLine(thing);
    }
}

Practical LearningPractical Learning: Sharing a Class

  1. On the main menu, click VIEW -> Class View
  2. In the Class View, double-click DepartmentStore1 to expand it
  3. In the top section of the body of the Class View, right-click StoreItem and click Go To Definition
  4. Press Home, type public and a space to change the document:
    public class StoreItem
    {
    }

Garbage Collection

When you initialize a variable using the new operator, you are in fact reserving some space in the heap memory. The memory is "allocated" for the variable. When that variable is no longer needed, such as when your program closes, it (the variable) must be removed from memory and the space it was using can be made available to other variables or other programs. This is referred to as garbage collection. In the past, namely in C/C++, this was a concern for programmers because they usually had to remember to manually delete such a variable (a pointer) and free its memory.

The .NET Framework solves the problem of garbage collection by "cleaning" the memory after you. This is done automatically when necessary so that the programmer doesn't need to worry about this issue.

The Fields of a Class

Consider a class named House:

public class House
{
}

The section between the curly brackets, { and }, of a class is referred to as its body. In the body of a class, you can create a list of the parts that make up the class. These parts are created as member variables. In C#, a variable created in the body of a class is called a field. Each field is declared as normal variable with a name and a data type. The name of a variable follows the same rules we reviewed for names of variables.

For example, here are the characteristics that make up a house, declared as the parts of the above class and each declared as a variable:

public class House
{
    string propertyNumber;
    string propertyType;
    int stories;
    int bedrooms;
    double value;
}

A Null Field

If you want to indicate that a field of primitive type can hold a null value, you can add a question mark to it to indicate that the field may carry null. Here are examples:

public class House
{
    string propertyNumber;
    string? propertyType;
    int? stories;
    int? bedrooms;
    double? value;
}

If you use this technique, there are rules you must observe after that.

The variables declared in the body of a class are referred to as its member variables and each member variable is referred to as a field. The fields can be any type we have seen in the previous lesson. When creating a class, it is your job to decide what your object is made of.

Author Note

New Convention:

From now on, in our lessons, to refer to a field that belongs to a class, we may write

ClassName.FieldName

This means that we are referring to the field FieldName that is a member of the class ClassName.


Practical LearningPractical Learning: Adding Fields to a Class

Access Modifiers of Class Members

The Private Members of a Class

The parts of an object fall into two main categories: those you can touch and those you don't have access to. For example, for a car parked at the mall, you can see or touch its doors and its tires but you don't see its engine or its spare tire, you don't even know if it has one. The parts of an object that you have access to are referred to as public.

The Public Members of a Class

The parts of a class that must be hidden are referred to as private.

A C# class also recognizes that some parts of a class can be made available to other classes and some other parts can be hidden from other classes. A part that must be hidden from other classes is private and it can be declared starting with the private keyword. If you declare a member variable and want to make it available to other classes, you must start its name with the public keyword. The public and private keywords are referred to as access level.

By default, if you declare a member variable (or anything else) in a class but don't specify its access level, the member is considered private and cannot be accessed from outside, that is by a non-member, of that class. Therefore, to make a member accessible by other classes, you must declare it as public.

You can use a mix of public and private members in a class and there is no rule on which access level should be listed first or last. Here are examples:

public class House
{
    string propertyNumber;
    public string propertyType;
    int stories;
    public int bedrooms;
    private double value;
}

Just keep in mind that if you omit or forget the access level of a member of a class, the member is automatically made private. To reduce confusion as to what member is public or private, you should always specify the access level of a member variable.

public class House
{
    public string propertyNumber;
    public string propertyType;
    public int stories;
    public int bedrooms;
    public double value;
}

Practical LearningPractical Learning: Specifying the Access Modifiers of Fields

The Internal Members of a Class

We have seen that the public keyword is used to let objects of the same program and objects of other programs access the public member. The private keyword is used to let only members of a class access the (private) member of the class. If you want to create a member of a class so that only objects of the same program can access that member, you can mark it with the internal keyword. The differences between these keywords can be resumed as follows:

  If a class member is marked as
  public internal private
Members of its class can access this member Yes Yes Yes
Members of this program, including outside of the class, can access this member Yes Yes No
Objects outside of this program can access this member Yes No No

Initializing an Object

The Period Operator

After creating a member of a class, to access it from another class, first declare a variable from its class as we saw earlier. To actually access the member, use the period operator ".".

After declaring an instance of a class, you can access each of its members and assign it the desired value. Here is an example:

public class House
{
    internal int propertyNumber;
    internal string propertyType;
    internal int bedrooms;
    internal double value;
}
Single Family
public class Exercise
{
    static void Main()
    {
        var property = new House();

        property.propertyNumber = 283795;
        property.propertyType = "Single Family";
        property.bedrooms = 4;
        property.value = 652880;
    }
}

Remember that the primitive types can use a question mark to indicate that they may carry a null value:

public class House
{
    internal int? propertyNumber;
    internal string propertyType;
    internal int? bedrooms;
    internal double? value;
}

public class Exercise
{
    static void Main()
    {
        var property = new House();

        property.propertyNumber = 283795;
        property.propertyType = "Single Family";
        property.bedrooms = 4;
        property.value = 652880;
    }
}

As another technique to initialize an object, after the parentheses of the class, type an opening and a closing curly brackets {}. In the brackets, type the name of each property and assign the desired value to it. These initializations must be separated by commas. Here is an example:

class Contractor
{
    public string FirstName;
    public string LastName;
}

class Employment
{
    static void Main()
    {
        Contractor staff = new Contractor
        {
            FirstName = "Robert",
            LastName = "Dayne"
        };
    }
}

Copying an Object

If you aready have an object created from a class, you can assign it to another object created from the same class. This is the same as making a copy of an object. Here is an example:

class Contractor
{
    public string FirstName;
    public string LastName;
}

class Employment
{
    static void Main()
    {
        Contractor staff = new Contractor
        {
            FirstName = "Robert",
            LastName = "Dayne"
        };

        Contractor seasonal = new Contractor();

        seasonal = staff;
    }
}

When such an assignment has been made, both objects (in this case staff and seasonal) have the same value(s).

Accessing an Object

Once an object has been initialized, you can use the period operator to access it and retrieve its value:

public class House
{
    internal int? propertyNumber;
    internal string propertyType;
    internal int? bedrooms;
    internal double? value;
}

public class Exercise
{
    static void Main()
    {
        var property = new House();

        property.propertyNumber = 283795;
        property.propertyType = "Single Family";
        property.bedrooms = 4;
        property.value = 652880;

        System.Console.WriteLine("=//= Altair Realtors =//=");
        System.Console.WriteLine("Properties Inventory"); ;
        System.Console.Write("Property #:  ");
        System.Console.WriteLine(property.propertyNumber);
        System.Console.Write("Property Type:  ");
        System.Console.WriteLine(property.propertyType);
        System.Console.Write("Bedrooms:       ");
        System.Console.WriteLine(property.bedrooms);
        System.Console.Write("Market Value:  ");
        System.Console.WriteLine(property.value);
    }
}

This would produce:

=//= Altair Realtors =//=
Properties Inventory
Property #:  283795
Property Type:  Single Family
Bedrooms:       4
Market Value:  652880
Press any key to continue . . .

Practical LearningPractical Learning: Using a Class' Fields

  1. In the top section of the Code Editor, click DepartmentStore.cs to access that file
  2. Change it as follows:
    class DepartmentStore
    {
        static void Main()
        {
            StoreItem si = new StoreItem();
    
            si.itemNumber = 720823;
            si.itemName = "Cotton Seam Sheath Dress";
            si.size = "6";
            si.unitPrice = 158;
    
            System.Console.WriteLine("Department Store");
            System.Console.Write("Item #:     ");
            System.Console.WriteLine(si.itemNumber);
            System.Console.Write("Item Name:  ");
            System.Console.WriteLine(si.itemName);
            System.Console.Write("Item Size:  ");
            System.Console.WriteLine(si.size);
            System.Console.Write("Unit Price: ");
            System.Console.WriteLine(si.unitPrice);
            
            System.Console.ReadKey();
        }
    }
  3. Execute the application. This would produce:
    Department Store
    Item #:     720823
    Item Name:  Cotton Seam Sheath Dress
    Item Size:  6
    Unit Price: 158
  4. Close the message box
Dress

An Anonymous Type

We saw that, to use a class, you could first declare a variable for it and initialize it. Fortunately, you don't have to use a class to initialize an object. You can declare a variable that resembles an instance of a class and initialize it as you see fit. This is referred to as an anonymous type. To use it, declare the variable using the var keyword and use the new operator to allocate memory for it. Instead of using the name of a class, type an opening and a closing curly brackets after the new operator. In the curly brackets, state a name for each member as if it were the member of the class and initialize each member variable with the desired value. After the closing curly bracket, end the declaration with a semi-colon. Here is an example:

public class Exercise
{
    static void Main()
    {
        var BookInformation = new
        {
            Title = "Calculus 6e Edition",
            Pages = 1074,
            Cover = "Hard Back"
        };
    }
}

After initializing the anonymous type, you can access each one of its members using the name of the variable followed by the period operator, and followed by the member variable. Here is an example:

public class Exercise
{
    static void Main()
    {
        var BookInformation = new
        {
            Title = "Calculus 6e Edition",
            Pages = 1074,
            Cover = "Hard Back"
        };

        System.Console.WriteLine("=//= BookInformation =//=");
        System.Console.Write("Title:         ");
        System.Console.WriteLine(BookInformation.Title);
        System.Console.Write("Nbr of Pages:  ");
        System.Console.WriteLine(BookInformation.Pages);
        System.Console.Write("Type of Cover: ");
        System.Console.WriteLine(BookInformation.Cover);
    }
}

This would produce:

=//= BookInformation =//=
Title:         Calculus 6e Edition
Nbr of Pages:  1074
Type of Cover: Hard Back
Press any key to continue . . .

Remember that spreading the declaration on many lines only makes it easy to read. Otherwise, you can as well include everything on the same line.

public class Exercise
{
    static void Main()
    {
        var book = new { Title = "Calculus 6e Edition", Pages = 1074 };

        System.Console.WriteLine("=//= BookInformation =//=");
        System.Console.Write("Title:         ");
        System.Console.WriteLine(BookInformation.title);
        System.Console.Write("Nbr of Pages:  ");
        System.Console.WriteLine(BookInformation.pages);
    }
}

Managing the Fields of a Class

Introduction

To assist you with managing the fields of a class, the Code Editor is equipped with two combo boxes.

Field

The left combo box displays the classes that are inside of the current file. The right combo box displays the members of the class that is selected in the left combo box:

Fields

Accessing a Field

There are many ways you can access a field:

Renaming a Field

If you decide to use a different name for a field, you can change it. You can first locate the field in the file and use your know of text editing. As an alternative, after opening the file that contains the class, on the main menu, you can click EDIT -> Quick Replace, type the name of the field, and click Find Next or Replace. This approach is useful if you want to visit every part where the field is used. If you know for sure that you want to rename a field and everywhere it has been used, Microsoft Visual Studio can assist you.

To rename a field in Microsoft Visual Studio:

Practical LearningPractical Learning: Ending the Lesson


Previous Copyright © 2008-2019, FunctionX Next