Creating a Class

Public Classes and Namespaces

When you create a class in a namespace, you can mark that class with an access level, such as public. The rules are the same for a public class as we saw in the previous lesson. You just have to remember that the class is a member of the namespace. Here is an example:

namespace AltairRealtors
{
    public class House
    {
        public string PropertyType{ get; set; }
        public int    Bedrooms   ;
        public double marketValue;
    }
}

Partial Classes and Namespaces

When creating a class that is partial, you can make it a member of a namespace. There is no particular rule to follow, as long as you keep in mind that the class is a member of a namespace. Here is an example:

namespace NationalCensus
{
    partial class Person
    {
        public string FirstName;
        public string LastName ;
    }
}

Managing Classes

Introduction to the Class View

Microsoft Visual Studio provides many tools to help you create and manage the classes of your project. One of those tools is named the Class View. The Class View is not automatically available when you start a project. To display the Class View:

By default, the Class View displays in the same area as the Solution Explorer. The Class View displays the name of the current project:

Class View - Project

If you are working on a solution that involves many projects, the Class View would display each project on its node:

Class View - Project

To view the members of a class, expand the node of a project and click the name of the class.

Introduction

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

The Types Combo Box

The middle-top section of the Code Editor is the Types combo box. It holds a list of the classes in the file that is currently displaying. You can display the list if you click the arrow of the combo box:

Code Editor - The Types Combo Box

The Members Combo Box

The top-right section of the Code Editor displays a combo box named Members. The Members combo box holds a list of the members of the class selected in the Types combo box. Therefore, before accessing the members of a particular class, you must first select that class in the Types combo box. Then, when you click the arrow of the Members combo box, the members of only that class display:

Code Editor - The Members Combo Box

If you select an item from the Members combo box, the Code Editor jumps to that members and positions the cursor to the left of the member.

The Class View

One of the windows used 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

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 in Microsoft Visual Studio, it provides a better solution and would take care of everything behind the scenes.

To rename a class in Microsoft Visual Studio:

Practical LearningPractical Learning: Renaming a Class

  1. Click the tab with Program.cs and change the document as follows:
    using static System.Console;

The Default Class of a Project

If you create a Console Application in Microsoft Visual Studio, the studio creates file that contains a default class. That class is named Program. You can rename to any valid name you want.

Managing the Fields of a Class

Introduction

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

Field

The middle combo box displays the class that is currently selected. The right combo box displays the members, such as fields of the class:

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 knowledge of text editing. As an alternative, after opening the file that contains the class, on the main menu, click Edit -> Find & Replace -> Quick Find, 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:

Generating a Class

To create a class, 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.

Constants

Introduction

Suppose you intend to use a number such as 39.37 over and over again. Here is an example:

using static System.Console;

double meter, inch;
		
meter = 12.52;
inch = meter * 39.37;

Write(meter);
Write(" = ");
Write(inch);
WriteLine("in\n");

Here is an example of running the program:

12.52 = 492.9124in

A constant is a value that never changes such as 244, "ASEC Mimosa", or 39.37. These are constant values you can use in your program any time. You can also declare a variable and make it a constant; that is, use it so that its value is always the same.

To let you create a constant, C# provides the const keyword. Type it to the left of the data type of a variable. When declaring a constant, you must initialize it with an appropriate value. Here is an example:

const double ConversionFactor = 39.37;

Once a constant has been created and it has been appropriately initialized, you can use its name where the desired constant would be used. Here is an example of a constant variable used various times:

using static System.Console;

const double conversionFactor = 39.37;
double meter, inch;

meter = 12.52;
inch = meter * conversionFactor;

Write(meter);
Write(" = ");
Write(inch);
WriteLine("in\n");

meter = 12.52;
inch = meter * conversionFactor;

Write(meter);
Write(" = ");
Write(inch);
WriteLine("in\n");

meter = 12.52;
inch = meter * conversionFactor;

Write(meter);
Write(" = ");
Write(inch);
WriteLine("in\n");

This would produce:

12.52 = 492.9124in

12.52 = 492.9124in

12.52 = 492.9124in

To initialize a constant variable, the value on the right side of "=" must be a constant or a value that the compiler can determine as constant. Instead of using a known constant, you can also assign it another variable that has already been declared as constant.

Constant Fields in a Class

When creating a field in a class, if you know that the value of that field will never change, create that field as a constant. That is, precede the data type of the field with the const keyword. Of course, you must initialize the field. Here is an example:

public class CustomerOrder
{
    const double originalPrice = 124.50;

    private int discountRate = 20;
    private double discountAmount = 0;
}

If the field will be accessed outside the class, you should mark it with the public or the internal keyword. If the field will be accessed only inside the class, you can omit any access keyword or mark it as private. After creating the field, you can use it and make sure you don't change its value. Here is an example:

using static System.Console;

CustomerOrder custOrder = new CustomerOrder();

custOrder.PresentCustomerOrder();

public class CustomerOrder
{
    const double originalPrice = 124.50;

    private int discountRate      = 20;
    private double discountAmount = 0;
    private double markedPrice    = 0;
    private double number_of_days_in_store = 75;

    private void EvaluateDiscount()
    {
        if (number_of_days_in_store is <= 45)
            discountRate = 25;
    }

    private void ProcessOrder()
    {
        discountAmount = originalPrice * discountRate / 100.00;

        markedPrice = originalPrice - discountAmount;
    }

    public void PresentCustomerOrder()
    {
        EvaluateDiscount();
        ProcessOrder();

        WriteLine("Fun Department Store");
        WriteLine("----------------------------------");
        WriteLine($"Original Price:  {originalPrice}");
        WriteLine($"Days in Store:   {number_of_days_in_store}");
        WriteLine($"Discount Rate:   {discountRate:n}");
        WriteLine($"Discount Amount: {discountAmount:n}");
        WriteLine($"Marked Price:    {markedPrice:n}");
        WriteLine("==================================");
    }
}

This would produce:

Fun Department Store
----------------------------------
Original Price:  124.5
Days in Store:   75
Discount Rate:   20.00
Discount Amount: 24.90
Marked Price:    99.60
==================================

Press any key to close this window . . .

Read-Only Constants

A Read-Only Field in a Class

When creating a field of a class, one of the decisions you must make is how the field would get its value(s). To create a field so that objects outside the class can only view its value but cannot change it while the value can be changed inside the class, create that field as read-only. To do this, when creating the field in the class, precede its data type with the readonly keyword. Here is an example:

public class Circle
{
    readonly double PI;
}

You can mark the field with an access level such as private or public, depending on your intentions.

To specify the value of a read-only field, use a constructor, such as the default constructor, to initialize the field. Here is an example:

public class Circle
{
    private double r;

    private readonly double PI;

    public Circle()
    {
       	PI = 3.14;
    }
}

The only difference between a constant variable and a read-only field is that a constant variable must be initialized when creating it. On the other hand, you can create more than one constructor in a class, then assign the same or a different value in each constructor to the read-only field. This means that, because you can initialize a read-only field in a constructor, if you have different constructors, you can also have different values for the same read-only field. Here are examples:

public class Circle
{
    private double r;

    private readonly double PI;

    public Circle()
    {
       	PI = 3.14;
    }

    public Circle(double rad)
    {
       	r = rad;
        PI = 3.14159;
    }

    public double CalculateDiameter()
    {
       	return r * 2;
    }

    public double CalculateArea()
    {
       return r * r * PI;
    }
}

Instead of a constant value, the value of a read-only field can come from an expression. If the value held by a read-only field is gotten from an expression, then the field must be initialized in the(a) constructor with the desired expression.

We know that a constant variable must be initialized when it is created. Although a read-only variable seems to follow the same rule, it doesn't. Remember that you don't need to initialize a read-only variable when you declare it since you can do this in the(a) constructor of the class. Also, because a constructor can be overloaded, a read-only field can hold different values depending on the particular constructor that is accessed at a particular time, but the value of a constant variable cannot change: it is initialized once, in the class (or in a method) and it keeps that value throughout the class (or method).

ApplicationPractical Learning: Creating and Using a Read-Only Field

  1. You can initialize a read-only field in the (a) constructor of its class. For an example, change the Circle class as follows:
    namespace PlanarCurves3.Models
    {
        public class Circle
        {
            public readonly double PI;
    
            public double Radius { get; set; }
    
            public Circle()
            {
                PI = 3.14;
                Radius = 0.00;
            }
    
            public double CalculateDiameter()
            {
                return Radius * 2.00;
            }
    
            public double CalculateArea()
            {
                return Radius * Radius * PI;
            }
        }
    }
  2. Click the Geometry.cs tab
  3. Change the code of the event as follows:
    using PlanarCurves3.Models;
    using static System.Console;
    
    var round = new Circle();
    
    WriteLine("=====================================");
    WriteLine("Enter the value to process the circle");
    Write("Radius:   ");
    round.Radius = double.Parse(ReadLine());
    
    WriteLine("=====================================");
    WriteLine("Geometry - Circle Summary");
    WriteLine("-------------------------------------");
    WriteLine("Radius:   {0}", round.Radius);
    WriteLine("PI:       {0}", round.PI);
    WriteLine("Diameter: {0}", round.CalculateDiameter());
    WriteLine("Area:     {0}", round.CalculateArea());
    Write("=====================================");
  4. To execute the application, on the main menu, click Debug -> Start Without Debugging:
  5. For the Side, type 5377.96 and press Enter:
    =====================================
    Enter the value to process the circle
    Radius:   5377.96
    =====================================
    Geometry - Circle Summary
    -------------------------------------
    Radius:   5377.96
    PI:       3.14
    Diameter: 10755.92
    Area:     90816504.811424
    =====================================
    
    Press any key to close this window . . .
  6. To close the window and return to your programming environment, press K
  7. Click the Circle.cs tab to access the class
  8. Because a read-only field can be initialized in a constructor, each constructor can assign a different value to the field. As a result, a read-only field can have different values. When you create an object, the constructor you choose will provide the value of the read-only field. For examples, change the Circle class as follows:
    namespace PlanarCurves3.Models
    {
        public class Circle
        {
            public readonly double PI;
    
            public double Radius { get; set; }
    
            public Circle()
            {
                PI = 3.14;
                Radius = 0.00;
            }
    
            public Circle(double rad)
            {
                Radius = rad;
                PI = 3.14159;
            }
    
            public double CalculateDiameter()
            {
                return Radius * 2.00;
            }
    
            public double CalculateArea()
            {
                return Radius * Radius * PI;
    	    }
        }
    }
  9. Click the Geometry.cs tab to access the code
  10. Change the code as follows:
    using PlanarCurves3.Models;
    using static System.Console;
    
    WriteLine("=====================================");
    WriteLine("Enter the value to process the circle");
    Write("Radius:   ");
    double rad = double.Parse(ReadLine());
    
    var round = new Circle(rad);
    
    WriteLine("=====================================");
    WriteLine("Geometry - Circle Summary");
    WriteLine("-------------------------------------");
    WriteLine("Radius:   {0}", round.Radius);
    WriteLine("PI:       {0}", round.PI);
    WriteLine("Diameter: {0}", round.CalculateDiameter());
    WriteLine("Area:     {0}", round.CalculateArea());
    Write("=====================================");
  11. To execute the project, on the main menu, click Debug -> Start Without Debugging
  12. For the Side, type 1327.97
    =====================================
    Enter the value to process the circle
    Radius:   1327.97
    =====================================
    Geometry - Circle Summary
    -------------------------------------
    Radius:   1327.97
    PI:       3.14159
    Diameter: 2655.94
    Area:     5540207.539496231
    =====================================
    
    Press any key to close this window . . .
  13. To close the window and return to your programming environment, press K
  14. Click the Circle.cs tab and change the Circle class as follows:
    namespace PlanarCurves3.Models
    {
        internal class Circle
        {
            public readonly double PI;
    
            public Circle() : this(0.00)
            {
                PI = 3.14;
            }
    
            public Circle(double rad)
            {
                Radius = rad;
                PI = 3.14159;
            }
    
            public double Radius { get; set; }
    
            public double CalculateDiameter() => Radius * 2.00;
    
            public double CalculateArea()     => Radius * Radius * PI;
        }
    }
  15. To execute the project, on the main menu, click Debug -> Start Without Debugging
  16. For the Side, type 1003.77
    =====================================
    Enter the value to process the circle
    Radius:      1003.77
    =====================================
    Geometry - Circle Summary
    -------------------------------------
    Radius:   1003.77
    PI:       3.14159
    Diameter: 2007.54
    Area:     3165322.2397045107
    =====================================
    
    Press any key to close this window . . .
  17. To close the window and return to your programming environment, press L
  18. Start a new Console App that support .NET 9.0 (Standard Term Support) and named Volumetrics1
  19. To create a new folder, in the Solution Explorer, right-click Volumetrics1 -> Add -> New Folder
  20. Type Models as the name of the folder
  21. In the Solution Explorer, right-click Models -> Add -> Class...
  22. In the middle list of the Add New Item dialog box, make sure the Class option is selected.
    Change the file Name to Rectangle
  23. Click Add

Practical LearningPractical Learning: Ending the Lesson


Previous Copyright © 2001-2025, FunctionX Monday 03 March 2025, 12:48 Next