C# – Casting between classes that share the same interface

ccastinginterface

I have two interfaces IHeaderRow, and IDetailRow

I then have an object that implements both RawRow:IHeaderRow, IDetailRow

I then need to cast it to HeaderRow which implements IHeaderRow.

But when I try, it ends up being null or giving an exception.

I can cast ObjectRawRow to either interface IHeaderRow, or IDetailRow

var ObjectIHeaderRow = ObjectRawRow as IHeaderRow;
var ObjectIDetailRow = ObjectRawRow as IDetailRow;

But I can not cast ObjectRawRow to HeaderRow , or ObjectIHeaderRow to HeaderRow.

It throws the error Cannot convert source type 'IA' to target type 'A'

I need to cast it into the actual class HeaderRow.

Thoughts?

EDIT:

Even though setting up an explicit cast took care of the issue I thought I'd provide an answer to the people wondering, WHY I was doing what I was.

In short, I'm sequentially processing a file. Line by line. I read the row into RawRow, and until I look at a few values, I don't actually know what type of row it is going to be. I then wanted to cast it to the proper type.

Best Answer

You can only implicitly cast objects to types they inherit from or implement - since RawRow doesn't derive from HeaderRow, it's not possible.

Depending on your requirements, you could overcome this by writing an explicit conversion operator, creating a HeaderRow constructor that accepts a RawRow as its prototype, or by modifying your code to operate on an IHeaderRow.