Cannot convert type ‘{your_type}’ to ‘T’, chaining casts to correct this error

Photo by Florian Olivo on Unsplash

The below .NET C# code will trigger a compiler error.

The reason for this error is that the compiler doesn’t know if this cast is valid.

Thus the compiler throws an error saying something like: Cannot convert type ‘{some_type}’ to ‘T’.

A simple trick to resolve this issue is to chain your casts, like below:

Because the compiler trusts casting almost any C# expression to (object), the compiler allows the first cast.

Second, the compiler will implicitly trust your cast from object to any T.

Of course, with this method, you as the developer are responsible to make sure that this code is indeed safe.

But, in cases where you know that a cast is safe, double-casting to `object as an intermediate step, allows you to quickly resolve cast failures.

If you like this article, please clap below

Remember, you can clap as many times as you like!

Also, to get more technical tips like this, follow me NOW.

I’m a software engineer turned entrepreneur. Technology, SEO, and Marketing are my passions. Over the last 36-months my ads have made $1.36+ million in sales.