Custom Type Examples - CSharp Language Basics

CSharp examples for Language Basics:Data Type

Introduction

We can build complex types from primitive types.

In this example, we will define a custom type named UnitConverter-a class that serves as a blueprint for unit conversions:

Demo Code

using System;//from   ww  w . j ava  2 s  .c o  m
public class UnitConverter
{
   int ratio;                                                 // Field
   public UnitConverter (int unitRatio) {
      ratio = unitRatio;
   } // Constructor
   public int Convert   (int unit)    {
      return unit * ratio;
   } // Method
}
class Test
{
   static void Main()
   {
      UnitConverter feetToInchesConverter = new UnitConverter (12);
      UnitConverter milesToFeetConverter  = new UnitConverter (5280);
      Console.WriteLine (feetToInchesConverter.Convert(30));    // 360
      Console.WriteLine (feetToInchesConverter.Convert(100));   // 1200
      Console.WriteLine (feetToInchesConverter.Convert(milesToFeetConverter.Convert(1)));   // 63360
   }
}

Result


Related Tutorials