Friday, March 29, 2019

Cast one dynamic to the type of another in c#

I'm trying to write a generic function that compares expected results from reflection (but where the expectation is provided in configuration by users rather than at design time) with the actual results for arbitrary properties.



I'm running into an issue where the expected type doesn't always reflect the returned type by default - e.g. my reflection result (in a dynamic) may be an int, where the expected result is an enum member (inheriting from int).



I'd like, therefore to do the following:



if ((dCurrentValue as typeof(this.CheckValue)) != this.CheckValue) { oOut = false; }



however, this doesn't seem to work. From fumbling around the web, I've managed to find that either System.Activator or Convert.ChangeType() may be my friends. However, so far they're not working as I'd expect - e.g.:



dCurrentValue = Convert.ChangeType(dCurrentValue, this.CheckValue.GetType());


throws an exception (for the pair that alerted me to the issue) that Invalid cast from 'System.Int32' to 'Microsoft.Office.Core.MsoTriState' - which I know to be wrong, since:



(int)Microsoft.Office.Core.MsoTriState.msoTrue == -1                                    // true
((Microsoft.Office.Core.MsoTriState)(-1)) == Microsoft.Office.Core.MsoTriState.msoTrue // true



NB that whilst I could put a shim in to solve for MsoTriState (i.e. check type of this.CheckValue, and explicit cast if applicable), I'd rather do this in a way that'll work for unknown enum entries.



EDIT: Thanks to the comments below, I've added a test before my tests of the form:



if (((Type) this.CheckValue.GetType()).IsEnum)
{
dCurrentValue = Enum.Parse(this.CheckValue.GetType(), dCurrentValue.ToString());
}



which fixes my immediate issue. My guess is this combined with Convert.ChangeType() (which as I've mentioned, doesn't seem to like converting Enums to Ints) will cover most situations.

No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...