Home

Introduction to Built-In Interfaces

Built-In Interfaces and Classes

Introduction

The .NET Framework provides a large collection of interfaces that 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 and create a new Windows Forms application named FormattingValues
  2. Design the form as follows:

    Introducing Built-In Interfaces

    Control (Name) Text
    Label   Decimal Number:
    TextBox txtDecimalNumber
    Label   Natural Number:
    TextBox txtNaturalNumber
    Button Convert btnConvert
    Label   Fixed:
    TextBox txtDecimalNumberFixed
    Label   Decimal:
    TextBox txtNaturalNumberDecimal
    Label   Currency:
    TextBox txtDecimalNumberCurrency
    Label   Currency:
    TextBox txtNaturalNumberCurrency
    Label   Scientific:
    TextBox txtDecimalNumberScientific
    Label   Scientific:
    TextBox txtNaturalNumberScientific
    Label   Natural:
    TextBox txtDecimalNumberNatural
    Label   Natural:
    TextBox txtNaturalNumberNatural
    Label   General:
    TextBox txtDecimalNumberGeneral
    Label   Hexadecimal:
    TextBox txtNaturalNumberHexadecimal
  3. Double-click the Convert button
  4. Right-click inside the Code Editor and click Remove and Sort Usings

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. Implement the event as follows:
    using System;
    using System.Windows.Forms;
    
    namespace FormattingValues
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }
    
            (int, double) GetNumbers()
            {
                int    x = 0;
                double y = 0.00;
    
                try
                {
                    y = double.Parse(txtDecimalNumber.Text);
                }
                catch (FormatException)
                {
                    MessageBox.Show("Make sure you enter a valid decimal number.", "Number Formatting");
                }
    
                try{
                    x = int.Parse(txtNaturalNumber.Text);
                }
                catch (FormatException)
                {
                    MessageBox.Show("You must provide an appropriate natural number.", "Number Formatting");
                }
    
                return (x, y);
            }
    
            private void btnConvert_Click(object sender, EventArgs e)
            {
                (int natural, double fractional) values = GetNumbers();
    
                txtDecimalNumberFixed.Text = values.fractional.ToString("f");
                txtNaturalNumberDecimal.Text = values.natural.ToString("D");
                txtNaturalNumberCurrency.Text = values.natural.ToString("c");
                txtDecimalNumberCurrency.Text = values.fractional.ToString("c");
                txtDecimalNumberScientific.Text = values.natural.ToString("e");
                txtNaturalNumberScientific.Text = values.fractional.ToString("e");
                txtDecimalNumberNatural.Text = values.fractional.ToString("n");
                txtNaturalNumberNatural.Text = values.natural.ToString("n");
                txtDecimalNumberNatural.Text = values.fractional.ToString("n");
                txtNaturalNumberNatural.Text = values.natural.ToString("n");
                txtDecimalNumberGeneral.Text = values.fractional.ToString("g");
                txtNaturalNumberHexadecimal.Text = values.natural.ToString("x");
            }
        }
    }
  2. To execute the application to see the results, press Ctrl + F5

    Formatting Some Values

  3. In the Decimal Number text box, type 13972418.65 and press Tab
  4. In the Natural Number text box, type 13972418

    Formatting Some Values

  5. Click the Convert button:

    Formatting Some Values

  6. Change the values in the Decimal Number and the Natural Number text boxes, such as 37948048.79 and 37948048
  7. Click the Convert button:

    Formatting Some Values

  8. 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, plural) you want to consider. The comparison is simple if you are dealing with values of primitive types. 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:

using System;

public class Program
{
    public static void Main()
    {        
        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);

        Console.WriteLine("Red Oak High School");
        Console.WriteLine("-----------------------");
        
        Console.WriteLine("Comparison by Student Number");
        Console.Write("First == Second: ");
        Console.WriteLine(std1.CompareTo(std2));
        Console.Write("First == Third:  ");
        Console.WriteLine(std1.CompareTo(std3));
        Console.WriteLine("=============================");

        return;
    }
}

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);
    }
}

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, 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-2020, FunctionX Next