Reputation: 3082
I have copied a piece of legacy code written in VB.Net which when converted to C# has produced the following:
///<summary>
///Test whether SSAC should be serialized
///</summary>
public virtual bool ShouldSerializeSSAC()
{
if (_shouldSerializeSSAC)
{
return true;
}
return (_sSAC != (SSAC_Type)null);
}
It is throwing an error stating it cannot convert because it is a non-nullable type. The code for the SSAC is as follows:
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Xml", "4.6.81.0"), System.SerializableAttribute()]
public enum SSAC_Type
{
///<remarks/>
A,
///<remarks/>
B,
///<remarks/>
C,
///<remarks/>
D,
///<remarks/>
E,
///<remarks/>
F,
///<remarks/>
G,
///<remarks/>
H,
///<remarks/>
J
}
In VB.Net this function was as follows:
Public Overridable Function ShouldSerializeSSAC() As Boolean
If _shouldSerializeSSAC Then
Return True
End If
Return (_sSAC <> CType(Nothing, SSAC_Type))
End Function
While the SSAC class was as follows:
<System.CodeDom.Compiler.GeneratedCodeAttribute("System.Xml", "4.6.81.0"),
System.SerializableAttribute()>
Public Enum SSAC_Type
'''<remarks/>
A
'''<remarks/>
B
'''<remarks/>
C
'''<remarks/>
D
'''<remarks/>
E
'''<remarks/>
F
'''<remarks/>
G
'''<remarks/>
H
'''<remarks/>
J
End Enum
How can I update the C# code to fix this error?
Upvotes: 1
Views: 69
Reputation: 6542
'Nothing' when applied to an enum instance is always '0' in VB, whether or not the first value of the enum is explicitly set to anything else. That is, the actual first value of the enum is irrelevant. So the C# equivalent to your method is:
public virtual bool ShouldSerializeSSAC()
{
if (_shouldSerializeSSAC)
return true;
return (_sSAC != 0);
}
Upvotes: 0
Reputation: 43743
Well, "fix" may not be the best term to use here, since it was probably unintended behavior in the VB code. But, if by "fix", you mean, how do you make it work the same, then the answer is that the C# code should return (_sSAC != SSAC_Type.A)
. To actually correct it, _sSAC
should be declared as SSAC_Type?
(nullable), then you could just return _sSAC.HasValue
. The reason it worked in VB is because Nothing
in VB is not exactly equivalent to null
in C#. Nothing
actually means the default value for any given type, so for an integer, like an enum, the default is 0.
Upvotes: 2