Type conversion example in C# .NET using the IConvertible interface

In this we saw how to convert between numeric types explicitly and implicitly. There are other ways to implement conversions in C#. You must have come across the System.Convert static methods such as System.ConvertToInt32 or System.ConvertToByte.

You can implement your own conversions by implementing the IConvertible interface. Consider the following object:

public class House
{
	public double Area { get; set; }
	public int NumberOfRooms { get; set; }
	public string Address { get; set; }
	public bool ForSale { get; set; }
        public DateTime DateBuilt { get; set; }
}

Say you’d like to convert – or cast – a House object…

House house = new House()
{
	Address = "London",
	Area = 123.45,
	ForSale = false,
	NumberOfRooms = 4,
        DateBuilt = DateTime.UtcNow.AddYears(-2)
};

…into a double, i.e. the Area property.

The following code will throw an InvalidCastException:

double d = Convert.ToDouble(house);

The solution is to implement the IConvertible interface. Here comes a warning: this interface comes with 17 methods such as ToDecimal or ToUInt16. You don’t need to implement all of them as not everything will make sense for your object. E.g. it’s probably meaningless to convert the above House object to a byte or char. Here are the methods that I’ve implemented. I left the rest with the default throw new NotImplementedException(); body:

public TypeCode GetTypeCode()
{
	return TypeCode.Object;
}

public bool ToBoolean(IFormatProvider provider)
{
	return ForSale;
}

public DateTime ToDateTime(IFormatProvider provider)
{
	return DateBuilt;
}

public double ToDouble(IFormatProvider provider)
{
	return Area;
}

public int ToInt32(IFormatProvider provider)
{
	return NumberOfRooms;
}

public string ToString(IFormatProvider provider)
{
	return Address;
}

Suddenly the following conversions will be possible:

double d = Convert.ToDouble(house);
DateTime dt = Convert.ToDateTime(house);
int z = Convert.ToInt32(house);
String s = Convert.ToString(house);
bool b = Convert.ToBoolean(house);

View all various C# language feature related posts here.

Advertisements

About Andras Nemes
I'm a .NET/Java developer living and working in Stockholm, Sweden.

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

ultimatemindsettoday

A great WordPress.com site

iReadable { }

.NET Tips & Tricks

Robin Sedlaczek's Blog

Developer on Microsoft Technologies

HarsH ReaLiTy

A Good Blog is Hard to Find

Softwarearchitektur in der Praxis

Wissenswertes zu Webentwicklung, Domain-Driven Design und Microservices

the software architecture

thoughts, ideas, diagrams,enterprise code, design pattern , solution designs

Technology Talks

on Microsoft technologies, Web, Android and others

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog

Anything around ASP.NET MVC,WEB API, WCF, Entity Framework & AngularJS

Cyber Matters

Bite-size insight on Cyber Security for the not too technical.

Guru N Guns's

OneSolution To dOTnET.

Johnny Zraiby

Measuring programming progress by lines of code is like measuring aircraft building progress by weight.

%d bloggers like this: