Home > Uncategorized > System.IConvertible – Its not a Ferrari

System.IConvertible – Its not a Ferrari

You might be familiar with the System.Convert class, which has a number of methods for converting from/to different types. For example:

short s = Convert.ToInt16(int.MaxValue);

We live in a world of casting and you might find this code somewhat pointless. After all, it will still raise StackOverflowException and lose precision with floating poing conversions, so what’s the point?

The convert class is capable of converting an instance of ANY type into one of the common base types (sting, int, ulong, char, etc). If a type implements the System.IConvertible interface, it can define how conversions of that type will occur.

Lets consider a (not so practical) example. Say we have a product class with the following properties:

public int ProductId { get; set; }
public DateTime DateAvailable { get; set; }
public string Name { get; set; }

Our Product class also has a parameterless constructor. In this example, we also make the Product class implement the IConvertible interface. This forces us to implement 16 methods and 1 property. Those methods all relate directly to conversion. For example, here’s the implementation of one of those methods:

public ulong ToUInt64(IFormatProvider provider) {
      return (UInt64)ProductId;
}

What we are saying here is that if someone tries to convert our Product instance to a ulong then it will simply assign the ProductId. Our test code looks like this:

Product p = new Product { Name="Car", DateAvailable=DateTime.Now, ProductId=7 };
UInt64 i = Convert.ToUInt64(p);
Console.WriteLine(i);

The output is the number "7" because that is how our implementation of IConvertible tells the Convert class to handle conversions to UInt64.

Simple eh?

 

About these ads
Categories: Uncategorized
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: