Home > C# .NET > C# .NET Tutorial 4: Converting between Types

C# .NET Tutorial 4: Converting between Types

Hello there! How are you? I hope you are all well. In this tutorial I will explain how we can convert between different types. It is important that you read tutorial 3 before attempting to read this tutorial. So let’s start.

C# unlike Visual Basic prohibits implicit conversion that lose precision. This means that in C# one cannot convert a double to an int. Implicit conversion is allowed only if the destination type can accomodate all possible values of the source type. This is called widening conversion:

double d = 1.0000001;
int i = 1;
d = i; //conversion allowed

If the range of the source type exceeds that of the destination type a narrowing conversion will take place or an explicit conversion. To perform explicit conversion in C# you need to use one of the following:

  • System.Convert – this can be used on types that implement the System.IConvertible interface.
  • (type) cast operator – used on types that define conversion operators.
  • type.ToString / type.Parse – between strings and base types; throws exception if conversion is not possible.
  • type.Parse / type.ParseExact – from string to a base type. Returns false if conversion is not possible.

Narrowing conversions fail if the source value exceeds the destination type range or if a conversion between the types is not defined.

Boxing and Unboxing

Boxing converts a value type to a reference type. Unboxing as you may have guessed correctly is converting a reference type to a value type. This example demonstrates how boxing work. We will convert an int (value type) to an Object (reference type):

int i = 29;
object o = (object) i;

Here is an example of unboxing:

object o = 123;
int i = (int) o;

Boxing and unboxing incur overhead so you should avoid them as much as possible. Boxing also occurs when you call virtual methods that a structure inherits from System.Object such as ToString. To avoid boxing:

  • Implement type-specific versions (overloads) for procedures that accept various value types.
  • Use generics whenever possible
  • Override the ToString, Equals, and GetHash virtual members when using structures.

Implementing Conversion in Custom Types

To define conversion on custom types you can do one of the following:

  • Define conversion operators to simplify narrowing and widening conversions between numeric types.
  • Override ToString and Parse to provide conversion between string and type.
  • Implement the System.IConvertible interface to allow conversions through System.Convert. Use this technique to enable culture-specific conversions.

Please not that conversion operators are new as from .NET 2.0.

In this example we will see how to define conversion operators:

struct TypeA
{
    public int value;

    //Allows implicit conversion from an integer
    public static implicit operator TypeA(int arg)
    {
        TypeA temp = new TypeA();
        temp.value = arg;
        return temp;
    }

    //Allows explicit conversion to an integer
    public static explicit operator int(TypeA arg)
    {
        return arg.value;
    }

    //Provides string conversion to avoid boxing
    public override string ToString()
    {
        return this.value.ToString();
    }
}

Now one can assign integers to the type directly as show here:

TypeA a;
int i;
//Widening conversion
a = 42;
//Narrowing conversion (must be explicit)
i = (int) a;
Console.WriteLine("a = {0} and i = {1}", a.ToString(), i.ToString());

To implement the System.IConvertible interface, add the IConvertible interface to the type definition. Then use Visual Studio to generate the 17 methods required by this interface. Automatically Visual Studio will include a throw exception for all the methods. You can leave them as they are and only change those methods you wish to implement. After you implement IConvertible, the custom type can be converted using the System.Convert as shown here:

TypeA a;
bool b;
a = 42;
//Convert using ToBoolean
b = Convert.ToBoolean(a);

Ok that’s it for today hope it was of interest to you. As always do leave your comments. In the next 4 tutorials we will be seeing input and output in C#. Until then enjoy!!!!


Categories: C# .NET
  1. No comments yet.
  1. No trackbacks yet.