Invalid cast from 'System.Boolean' to 'CslaSrd.SmartBool'.

Invalid cast from 'System.Boolean' to 'CslaSrd.SmartBool'.

Old forum URL: forums.lhotka.net/forums/t/7191.aspx


AKaplan posted on Monday, June 29, 2009

Using Csla.net 3.5.3 VB with the CslaSRD project. Converting a boolean to a cslasrd.smartbool is not possible. Why?

It is crashing here.

LoadProperty(Of SmartBool, Boolean)(_allowSitePartnersToContact, data.AllowSitePartnerToContact)

AKaplan replied on Monday, June 29, 2009

This error crashes in this method when converting a boolean to a smartbool at the specified point.

Public Function CoerceValue(ByVal desiredType As Type, ByVal valueType As Type, ByVal oldValue As Object, ByVal value As Object) As Object

If desiredType.Equals(valueType) Then
' types match, just return value
Return value

Else
If desiredType.IsGenericType Then
If desiredType.GetGenericTypeDefinition() Is GetType(Nullable(Of )) Then
If value Is Nothing Then
Return Nothing

ElseIf valueType.Equals(GetType(String)) AndAlso CStr(value) = String.Empty Then
Return Nothing
End If
End If
desiredType = Utilities.GetPropertyType(desiredType)
End If

If desiredType.IsEnum AndAlso _
(valueType.Equals(GetType(String)) OrElse _
[Enum].GetUnderlyingType(desiredType).Equals(valueType)) Then
Return [Enum].Parse(desiredType, value.ToString())
End If

If desiredType.Equals(GetType(SmartDate)) AndAlso oldValue IsNot Nothing Then
If value Is Nothing Then _
value = String.Empty
Dim tmp = DirectCast(oldValue, SmartDate)
tmp.Text = value.ToString
Return tmp
End If

If (desiredType.IsPrimitive OrElse desiredType.Equals(GetType(Decimal))) _
AndAlso valueType.Equals(GetType(String)) _
AndAlso String.IsNullOrEmpty(CStr(value)) Then
value = 0
End If

Try
If desiredType.Equals(GetType(String)) AndAlso value IsNot Nothing Then
Return value.ToString()
Else

'This is where it crashes.

Return Convert.ChangeType(value, desiredType)
End If
Catch
Dim cnv As TypeConverter = TypeDescriptor.GetConverter(desiredType)
If cnv IsNot Nothing AndAlso cnv.CanConvertFrom(valueType) Then
Return cnv.ConvertFrom(value)

Else
Throw
End If
End Try
End If

RockfordLhotka replied on Monday, June 29, 2009

CoerceValue() tries every technique I'm aware of to try and convert a value of one type to another. If it fails, there are two possible reasons:

  1. The type can't be converted
  2. There's yet another type conversion API built into .NET that I'm unaware of

At this point I'm reasonably confident that the reason will be number 1 - the type just can't be converted.

If the SmartBool type doesn't have casting operators or a type converter then it won't be convertable. You can look at the SmartBool code to see if it has similar operator code and/or type converter code like you'll see in Csla.SmartDate. Much of the SmartDate code deals with type conversion these days, so it is hard to miss :)

Copyright (c) Marimer LLC