(C# Language) Practice Exercise in C# - 1

Write a C# class called CData to hold a float type of quantity. This class also contains an enumeration of two members - Meter and Centimeter - to specify the unit of the quantity stored. Add a constructor and a public function called Convert. The Convert function converts the data to meter if the data held is in centimeters, and to centimeters if the data held is in meters. The Convert function displays the result correct to 2 decimal places. Test the function by creating an object in the main function.
(Rev. 03-Dec-2022)

Categories | About |     |  

Parveen,

Objectives of this Exercise

This exercise introduces you to

  1. Naming conventions in C#.
  2. enumerations in C#.
  3. The use of internal access modifier.
  4. Parameterized constructor.
  5. Interpolated string format and Console output.

Video Explanation (see it happen!)

Please watch the following youtube video:

The Solution

First of all create a project in Visual Studio and open the solution explorer. Add a class called CData. It will add a file called CData.cs. You can obtain the project from the downloads attached to this tutorial. Here I will discuss the class.

The code for the class is now explained step-by-step.


// source code is in the downloads attached  
// to this tutorial 

// pascal camel case name of the class 
// that starts with a capital letter 

// internal modifier for access within 
// the same assembly/project 
internal class CData
{
  internal enum QuantityType { Meter, CentiMeter };

  // internal, private members 
  // start with _camelNotation 
  QuantityType _unitOfQuantity;

  float _quantity;

  // parameter names are camel case 
  public CData(QuantityType unitOfQuantity, float quantity)
  {
    _unitOfQuantity = unitOfQuantity;

    _quantity = quantity;
  }

  public void Convert()
  {
    switch (_unitOfQuantity)
    {

      case QuantityType.CentiMeter:
        {
          float val = _quantity / 100;

          // string interpolation syntax 

          String result = $"{_quantity} cm = {val:F2} m";

          Console.WriteLine(result);

        }
        break;

      case QuantityType.Meter:
        {
          float val = _quantity * 100;

          String result = $"{_quantity} m = {val} cm";

          Console.WriteLine(result);
        }
        break;

      default:
        throw new NotImplementedException("case unknown.");

    }
  }
}

The class is internal class CData. By naming convention, a class, record, or struct is named in Pascal Camel case that starts with an upper case letter. The internal keyword tells that this class is visible only inside this project. It is meant for internal use of this project. Other possibilities are private, public, etc., but you will have to wait for knowing all that because experience is the best teacher.

After that we define a nested enumeration called internal enum QuantityType { Meter, CentiMeter };. The enumeration has been nested to the class because it is relevant only for the purposes of this class. The enumeration is called QuantityType. An instance member called _unitofQuantity has been added. The float datatype is same as you have in other programming languages. The naming convention requires that data members or fields be named with camel case starting with an underscore and lowercase letter. Notice that u is lowercase.

A parameterized constructor has been added next. The parameters of the contructor are in a camel case and they start with a lower case letter.

Finally, we have added the Convert function.

A switch on the _unitOfQuantity contains case labels. The case label for CentiMeter converts centimeter to meter by dividing the quantity by 100. Next we have constructed the display string.

The string starts with a dollar sign. Such a syntax is called string Interpolation syntax. The identifiers are specified in curly braces. The numeric format string for 2 decimal places is specified with a colon :F2. There are many format strings in dotnet but you will have to wait for knowing all that because experience is the best teacher. Today we have learned :F2. The string is next displayed with console writeline method.

The case label for meter can be completed similarly.

The default label for C# throws an exception called NotImplementedException. This is not of much use here because we have only two members in the enumeration. But if a code becomes complex then this trick helps us in debugging problems.

Next again open the solution explorer and complete the program.cs file.


// program.cs  

// create object 
CData data = new(CData.QuantityType.CentiMeter, 20.0f);

data.Convert();

  

We have created an object of the class and then called the Convert function.

Run the Program

Now we can run the program to verify that the output is as expected. The display is shown upto 2 decimal places.

We'll close it now thankyou!


This Blog Post/Article "(C# Language) Practice Exercise in C# - 1" by Parveen is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.