How is the InvalidCastException I’m encountering in my C# WPF application happening?
I’ve tried changing the line that should be offending from “cacheConsumptionStatus = ConsumptionStatusType.GetByKey(Convert.ToInt32(value));” to “cacheConsumptionStatus = (ConsumptionStatusType.)value;”, and the result is the same.
The result is even the same with that line commented out completely.
“cache” is of type BitArray, “hasValue” is bool, and “value” is object.
Relevant code:
Message.cs
...
switch(propID)
{
...
case 968:
cache[9] = hasValue;
if (hasValue)
{ <-- InvalidCastException -- Unable to cast object of type 'System.Int32' to type 'Enumerations.ConsumptionStatusType'.
cacheConsumptionStatus = ConsumptionStatusType.GetByKey(Convert.ToInt32(value));
}
videoManagerRef.events.FireOnMessageConsumptionStatus(this, cacheConsumptionStatus);
break;
...
ConsumptionStatusType.cs
using System.Collections.ObjectModel;
namespace Enumerations
{
public class ConsumptionStatusType : EnumBase<ConsumptionStatusType>
{
public static readonly ConsumptionStatusType CONSUMED = new ConsumptionStatusType(0, "CONSUMED");
public static readonly ConsumptionStatusType UNCONSUMED_SUPPRESSED = new ConsumptionStatusType(1, "UNCONSUMED_SUPPRESSED");
public static readonly ConsumptionStatusType UNCONSUMED_NORMAL = new ConsumptionStatusType(2, "UNCONSUMED_NORMAL");
public static readonly ConsumptionStatusType UNCONSUMED_ELEVATED = new ConsumptionStatusType(3, "UNCONSUMED_ELEVATED");
public ConsumptionStatusType(int key, string value)
: base(key, value)
{
}
public static ReadOnlyCollection<ConsumptionStatusType> GetValues()
{
return GetBaseValues();
}
public static ConsumptionStatusType GetByKey(int key)
{
return GetBaseByKey(key);
}
}
}
This problem was a reference problem and not a code problem: I was working on the debug referenced library, while the project was referencing the release .dll, which is why it didn’t matter what I changed in the debug .dll.