I am running into an issue that I have never encountered before with type casting.
I am trying to cast an object of type TextmlBatchDeleteDocument to System.String so I implemented an explicit type conversion operator to handle accomplish this.
public override string ToString()
{
return string.Format("{0}{1}", this.Collection, this.Name);
}
public static explicit operator string(TextmlBatchDeleteDocument doc)
{
return doc.ToString();
}
Success, the following works.
TextmlBatchDeleteDocument doc = new TextmlBatchDeleteDocument("name", "/collection/");
string someString = (string)doc;
However I am passing an object of type List<TextmlBatchDeleteDocument> to a third party function that requires an object to implement IList and it will eventually use the objects in the list as strings. This is where I run into trouble. I get this exception whenever I try to call the third party function.
Unable to cast object of type ‘NWDA_Common.Textml.TextmlBatchDeleteDocument’ to type ‘System.String’.
If my assumptions are correct I am passing the function an object of type List<TextmlBatchDeleteDocument> but it gets cast to IList which will then treat any object in my list as the base type System.Object. I did a test to confirm this theory and got the same exception. If I cast my object of type List<TextmlBatchDeleteDocument> to System.Object first then try to do a cast to a string it will throw an exception.
TextmlBatchDeleteDocument doc = new TextmlBatchDeleteDocument("name", "/collection/");
object docAsObj = doc;
string someString = (string)docAsObj;
Is there anyone who knows how to solve this problem or am I stuck with re-factoring and finding another way?
It sounds like the third party component really needs an
IListwhere each element is a string – so that’s what you’ll need to provide it with. Conversions aren’t applied polymorphically – it’s a compile-time choice based on the compile-time type of the source expression.Basically, you’ll need to perform the conversion yourself for each element, and pass a list of the converted items to the third party code.