Built-In Interfaces and Classes

Introduction

The .NET Framework provides a large collection of interfaces you can implement in your classes. Many of the classes available in the .NET Framework implement these interfaces. In some of your projects, you may have to implement one or more of the existing interfaces in your class.

Practical LearningPractical Learning: Introducing Built-In Interfaces

  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 ASP.NET Web Application (.NET Framework) and set the project Name to FormattingValues
  4. Click OK
  5. In the New ASP.NET Application dialog box, click Empty and click OK
  6. In the Solution Explorer, right-click FormattingValues -> Add -> Web Page (Razor v3)
  7. Change the file Name to Index
  8. Click OK

Formatting a Value

The collection of techniques and formulas used by a language to display its values is referred to as a format provider. When you use a variable that uses a particular formula to display its value, to help you specify the right formula, the .NET Framework provides the IFormatProvider interface. IFormatProvider is defined in the System namespace.

There are two main ways you can use the IFormatProvider interface. You can create a class and implement it. The IFormatProvider interface is equipped with only one method: GetFormat.

In most cases, you will use classes that already implement the IFormatProvider interface. Those classes are equipped with an overridden version of the ToString() method that uses a parameter of type IFormatProvider. Its syntax is:

public string ToString(IFormatProvider provider)

This method requires that you create an IFormatProvider object and pass it as argument. An alternative is to pass a string. This is possible with another version of the ToString() method whose syntax is:

public string ToString(string format)

This method takes a string as argument. The string can take a letter as one of the following:

Letter Description
c C Currency values
d D Decimal numbers
e E Scientific numeric display such as 1.45e5
f F Fixed decimal numbers
d D General and most common type of numbers
n N Natural numbers
r R Roundtrip formatting
x X Hexadecimal formatting
p P Percentages

Practical LearningPractical Learning: Formatting Some Values

  1. Change the document as follows:
    <!DOCTYPE html>
    <html>
    <head>
    <title>Values Formatting</title>
    <style>
    .left-label   { width: 125px }
    .middle-label { width: 125px }
    </style>
    </head>
    <body>
    @{ 
        decimal number = 13972418.65m;
        int natural = 13972418;
    
        if (IsPost)
        {
            number = Request["txtDecimalNumber"].AsDecimal();
            natural = Request["txtNaturalNumber"].AsInt();
        }
    }
    <form name="frmFormatting" method="post">
        <h3>Values Formatting</h3>
        <table>
            <tr>
                <td class="left-label">Decimal Number:</td>
                <td><input type="text" name="txtDecimalNumber" value="@number" />
                <td class="middle-label">Natural Number:</td>
                <td><input type="text" name="txtNaturalNumber" value="@natural" /></td>
            </tr>
        </table>
        <table>
          <tr>
             <td class="left-label">&nbsp;</td>
             <td style="text-align: center">
                <input type="submit" name="btnConvert" style="width: 435px" value="Convert" />
             </td>
          </tr>
        </table>
        <table>
            <tr>
                <td class="left-label">Fixed:</td>
                <td><input type="text" name="txtDecimalNumberFixed" value=@number.ToString("f") />
                <td class="middle-label">Decimal:</td>
                <td><input type="text" name="txtNaturalNumberDecimal" value="@natural.ToString("d")" /></td>
            </tr>
            <tr>
                <td>Currency:</td>
                <td><input type="text" name="txtDecimalNumberCurrency" value=@number.ToString("c") />
                <td>Currency:</td>
                <td><input type="text" name="txtNaturalNumberCurrency" value="@natural.ToString("c")" /></td>
            </tr>
            <tr>
                <td>Scientific:</td>
                <td><input type="text" name="txtDecimalNumberScientific" value=@number.ToString("e") />
                <td>Scientific:</td>
                <td><input type="text" name="txtNaturalNumberScientific" value="@natural.ToString("e")" /></td>
            </tr>
            <tr>
                <td>Natural:</td>
                <td><input type="text" name="txtDecimalNumberNatural" value="@number.ToString("n")" />
                <td>Natural:</td>
                <td><input type="text" name="txtNaturalNumberNatural" value="@natural.ToString("n")" /></td>
            </tr>
            <tr>
                <td>General:</td>
                <td><input type="text" name="txtDecimalNumberGeneral" value="@number.ToString("g")" />
                <td>Hexadecimal:</td>
                <td><input type="text" name="txtNaturalNumberHexadecimal" value="@natural.ToString("x")" /></td>
            </tr>
        </table>
    </form>
    </body>
    </html>
  2. To execute the application to see the results, press Ctrl + F5

    Formatting Some Values

  3. Enter some values in the top two text boxes, such as 37948048.79 and 37948048
  4. Click the Coonvert button:

    Formatting Some Values

  5. Close the form and return to your programming environment

Cloning an Object

Consider a class as follows:

using System;

public class Circle
{
    public Circle()
    {
        Radius = 0.00;
    }

    public Circle(double rad)
    {
        Radius = rad;
    }

    public double Radius { get; set; }
    public double Area { get { return Radius * Radius * Math.PI; } }
    public double Diameter { get { return Radius * 2; } }

    public double Circumferemce
    {
        get { return Diameter * Math.PI; }
    }
}

Copying an object consists of creating another sample of it and that contains the same values as the original. To make this operation available to your classes, you can implement an interface named ICloneable. The ICloneable interface is defined in the System namespace of the mscorlib.dll library.

The ICloneable interface is equipped with one method named Clone. Its syntax is:

object Clone();

To assist you with making a copy of a variable, the Object class is equipped with a method named MemberwiseClone. This means that all classes of the .NET Framework and any class you create in your C# application automatically inherits this method. The syntax of this method is:

protected Object MemberwiseClone();

When implementing the ICloneable interface, in your class, you can simply call the MemberwiseClone() method. Here is an example:

using System;

public class Cylinder : Circle,
                        ICloneable
{
    public double Height { get; set; }

    public Cylinder(double baseRadius, double height)
    {
        Radius = baseRadius;
        Height = height;
    }

    public double LateralArea
    {
        get
        {
            return Circumferemce * Height;
        }
    }

    public double Volume
    {
        get
        {
            return Area * Height;
        }
    }

    public object Clone()
    {
        return this.MemberwiseClone();
    }
}

Comparing Two Objects

Comparing two objects consists of finding out which one comes first, for whatever criterion (or criteria) you want to consider. The comparison is simple if you are dealing with values of primitive types (characters, numbers, strings, etc). For example, it is easy to know that 2 is lower than 5, but it is not obvious to compare two objects created from a composite type, such as two students, two cars, or two food items. Consider the following Student class:

public enum Genders { Male, Female, Unknown }

public class Student
{
    public Student(int number = 0, string first = "John",
                   string last = "Doe", double ag = 1,
                   Genders gdr = Genders.Unknown)
    {
        StudentNumber = number;
        FirstName     = first;
        LastName      = last;
        Age           = ag;
        Gender        = gdr;
    }

    public int     StudentNumber { get; set; }
    public string  FirstName     { get; set; }
    public string  LastName      { get; set; }
    public double  Age           { get; set; }
    public Genders Gender        { get; set; }
}

To assist you with comparing two objects, the .NET Framework provides various comparable interfaces. One of these interfaces is named IComparable. The IComparable interface is a member of the System namespace. Obviously, you must define what would be compared and how the comparison would be carried. For example, to compare two Student objects of the above class, you can ask the compiler to base the comparison on the student number. Here is an example:

using System;

public enum Genders { Male, Female, Unknown }

public class Student : IComparable
{
    public Student(int number = 0, string first = "John",
                   string last = "Doe", double ag = 1,
                   Genders gdr = Genders.Unknown)
    {
        StudentNumber = number;
        FirstName     = first;
        LastName      = last;
        Age           = ag;
        Gender        = gdr;
    }

    public int     StudentNumber { get; set; }
    public string  FirstName     { get; set; }
    public string  LastName      { get; set; }
    public double  Age           { get; set; }
    public Genders Gender        { get; set; }

    public int CompareTo(object obj)
    {
        Student std = (Student)obj;

        return std.StudentNumber.CompareTo(this.StudentNumber);
    }
}

Here is an example of comparing two Student objects:

<!DOCTYPE html>
<html>
<head>
<title>Red Oak High School</title>
</head>
<body>
<h3>Red Oak High School</h3>

@{
    Student std1 = new Student(294759, "Patricia", "Katts", 14.50, Genders.Female);
    Student std2 = new Student(294706, "Raymond",  "Kouma", 18.50, Genders.Male);
    Student std3 = new Student(747747, "Patricia", "Childs", 12.00, Genders.Female);
}
    
<p>Comparison by Student Number</p>
<p>First =&gt; Second: @std1.CompareTo(std2)</p>
<p>First =&gt; Third:  @std1.CompareTo(std3)</p>
</body>
</html>

In the same way, you can choose any other member of the class to base the comparison. An example would consist of comparing the last names of students or comparing each property of one object to the corresponding property of the other object.

Most of the .NET Framework's classes that need to perform comparison already implement the IComparable interface or one of its equivalents.

Disposing of an Object

Introduction

Most objects that are used in an application consume memory and other resources. Some objects use more resources than others. Whenever you have finished using an object, you should (mostly must) make sure you free the resources it was using. In traditional programming (C++, Object Pascal (Delphi), etc), you would add a destructor to your class. Then, in the destructor, you would call the method(s) from which your objects consume resources. Here is an example:

using System;

public class Book
{
    public int numberOfPages;

    public void Read()
    {
    }
}

public class Student
{
    public Book text;

    public Student()
    {
        text = new Book();
    }

    public void ReleaseTheResources()
    {
        
    }

    ~Student()
    {
        ReleaseTheResources();
    }
}

To assist you in dismissing the resources used in your application, the .NET Framework provides an interface named IDisposable. Most of the time, you will not need to implement this interface because most of the classes that are resource-intensive have already been created and you will just use them. Those classes directly or indirectly implement the IDisposable interface. Here is an example of a class that already implement the IDisposable interface:

public class ScrollableControl : Control,
		                 IComponent,
				 IDisposable
{
}

There are two main ways you will use the IDisposable interface. One way is that, if you have to, that is, if you judge it necessary, you can create a class that implements the IDisposable interface. The IDisposable interface is defined in the System namespace that is a member of the mscorlib.dll library. This means that you don't have to import any library to use it. The IDisposable interface contains only one method, named Dispose. Its syntax is:

void Dispose();

When implementing the interface, use this method to free the resources a variable of the class was using. After calling this method, remember that the destructor of a class is always called when the variable gets out of scope. For this reason, it is a good idea to create a destructor for the class and call the Dispose() method from it. Here is an example:

using System;

public class Book
{
    public int numberOfPages;

    public void Read()
    {
    }
}

public class Student : IDisposable
{
    public Book text;

    public Student()
    {
        text = new Book();
    }

    public void Dispose()
    {
        
    }

    ~Student()
    {
        Dispose();
    }
}

Using and Disposing of an Object

The second way you can use the IDisposable interface is the most important for us. To support the ability to release the resources that an object was using, the C# language provides an operator named using. The formula to use it is:

using(parameter) { }

As you can see, this operator uses the formula of a method (or function). It is equipped with parentheses and a body delimited by curly brackets. In the parentheses, declare the variable that will use the resources you are concerned with. Inside the brackets, use the variable anyway you want and that is appropriate. When the compiler reaches the closing curly bracket, it does what is necessary. For example, the compiler may have to close a connection that was used or it would delete the object that was consuming the resources. Here is an example of using using:

using System;

public class Book
{
    public int numberOfPages;

    public void Read()
    {
    }
}

public class Student : IDisposable
{
    public Book text;

    public Student()
    {
        text = new Book();
    }
    
    public void Buy()
    {
    }

    public void Dispose()
    {
       
    }

    ~Student()
    {
        Dispose();
    }
}

public class Exercise
{
    public int View()
    {
        using (Student std = new Student())
        {
            std.Buy();
        }

        return 0;
    }
}

Practical LearningPractical Learning: Ending the Lesson


Previous Copyright © 2001-2019, FunctionX Next