I'm running into an issue where a private library method is trying to convert from string to my custom type, and is getting an exception:
Invalid cast from 'System.String' to 'CustomStringValue'.
Stack Trace:
[System.InvalidCastException: Invalid cast from 'System.String' to 'CustomStringValue'.]
at System.Convert.DefaultToType(IConvertible value, Type targetType, IFormatProvider provider)
at System.String.System.IConvertible.ToType(Type type, IFormatProvider provider)
at System.Convert.ChangeType(Object value, Type conversionType, IFormatProvider provider)
at System.Convert.ChangeType(Object value, Type conversionType)
at Program.Main()
My test code is:
public class Program
{
public static void Main()
{
string s = "test2";
CustomStringValue csv1 = s;
CustomStringValue csv2 = (CustomStringValue)Convert.ChangeType(s, typeof(CustomStringValue));
Console.WriteLine(csv1);
}
}
public class CustomStringValue
{
public string customString;
public CustomStringValue(string value)
{
this.customString = value;
}
public static implicit operator string(CustomStringValue csv) => csv.customString;
public static implicit operator CustomStringValue(string s) => new CustomStringValue(s);
public override string ToString()
{
return this.customString;
}
}
The assigning of csv1 works fine, as expected, but the assignment at csv2 is what I'm fighting against. I had implemented IConvertible previously, but that didn't seem to resolve the issue. I cannot control the fact that Convert.ChangeType() is being called, but I'm trying to find a way to make that conversion work. I'm not sure if there's something in my CustomStringValue class that needs to be implemented, or possibly I'm just out of luck with this.
If it makes any difference to anyone, the functional code is used for test automation with SpecFlow, where I'm trying to use custom class names to increase the readability of auto-complete options in feature files.
CustomStringValue csv2 = (CustomStringValue)Convert.ChangeType(s, typeof(CustomStringValue));withCustomStringValue csv2 = (CustomStringValue)s;