Understanding CLS compliance and correct code
-
05-09-2019 - |
Question
I've attempted to create an abstracted control to manage some of the state in our application. However, I have run a foul of some CLS issues and was hoping that someone could provide some insight.
I have an enumeration as such:
<Flags()> _
Public Enum FormState
Read = 1
Edit = 2
Insert = 4
End Enum
And a class as such:
Public MustInherit Class Fields
Inherits System.Web.UI.UserControl
Public Property State() As Enumerators.FormState
Get
Return _State
End Get
Set(ByVal value As Enumerators.FormState)
_State = value
ToggleState(value)
End Set
End Property
Protected MustOverride Sub ToggleState(ByVal state As FormState)
End Class
When I attempt to compile this code I am left with a warning that the State property is not CLS compliant and neither is the state argument. How come? And how can I correct this problem to remove the warnings?
- I've attempted to add the <CLSCompliant(True)> attribute to both items with no luck
- I tried to disseminate the MSDN article Non-CLS-compliant 'MustOverride' member is not allowed in a CLS-compliant into the code with no results
- I've tried changing the accessors to
Friend
instead ofPublic
- I've tried specifying a type for the Enum (
Integer
andUInteger
)
Solution
Looking at your code, the enum seems to be part of a class called enumerators. The class is not listed in your code, but I'm assuming that you have full control over it.
The class needs to be tagged with the CLS compliant attribute as well.
OTHER TIPS
To remove the warnings add the following attributes so that the class, method and property look like this:
<CLSCompliant(False)> _
Public MustInherit Class Fields
Inherits System.Web.UI.UserControl
<CLSCompliant(False)> _
Public Property State() As Enumerators.FormState
Get
Return _State
End Get
Set(ByVal value As Enumerators.FormState)
_State = value
ToggleState(value)
End Set
End Property
<CLSCompliant(False)> _
Protected MustOverride Sub ToggleState(ByVal state As FormState)
End Class
This signifies to the compiler that you want the warnings removed and that you're aware your code is not CLSCompliant.
It could be that you do not have an item with value 0.