VarType to GetType()
-
01-06-2021 - |
Question
I am converting a VB.NET project to C# and I got stuck on this if-loop, could anyone help me convert this? I am assuming that i'll need to use the GetType()-method for this but I'm not sure how.
The Loop:
Private Sub oOpcGroup_DataChange(ByVal TransactionID As Integer, ByVal NumItems As Integer, ByRef ClientHandles() As Integer, ByRef ItemValues() As Object, ByRef Qualities() As Integer, ByRef TimeStamps() As Date)
Dim i As Integer
For i = 1 To NumItems
If VarType(ItemValues(i)) And Not VariantType.Array Then
txtSubValue.Text = ItemValues(i)
Else
MsgBox("Data type return error, returned array, expected single item", MsgBoxStyle.Critical, "Data Change Error")
Exit Sub
End If
Next i
Exit Sub
End Sub
This is what I have so far:
void oOpcGroup_DataChange(int TransactionID, int NumItems, ref Array ClientHandles, ref Array ItemValues, ref Array Qualities, ref Array TimeStamps) //Events OPCGroup
{
for (int i = 0; i < NumItems; i++)
{
if(){
}
else
{
MessageBox.Show("Expected single item.", "Data type return error.", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
}
}
Solution
Here is what I came up with, using the GetType() instead of the Information.VarType.
I did replace the MsgBox method call with a call to System.Windows.Forms.MessageBox.Show.
private void oOpcGroup_DataChange(int TransactionID, int NumItems, ref Array ClientHandles, ref Array ItemValues, ref Array Qualities, ref Array TimeStamps)
{
for (int i = 0; i < NumItems; i++)
{
var obj = ItemValues.GetValue(i);
if (obj != null && !obj.GetType().IsArray)
{
txtSubValue.Text = obj.ToString();
}
else
{
System.Windows.Forms.MessageBox.Show("Data type return error, returned array, expected single item", "Data Change Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
OTHER TIPS
Forget the automatic code converters, they frequently make mistakes in conversion, especially if they don't have full context available (declaration of ItemValues etc.)
I think the original VB code is incorrect in this case. The code will execute like this C# code:
int i = 0;
for (i = 1; i <= NumItems; i++) {
if ((Information.VarType(ItemValues[i]) & ~VariantType.Array) != 0) {
txtSubValue.Text = ItemValues[i];
} else {
Interaction.MsgBox("Data type return error, returned array, expected single item", MsgBoxStyle.Critical, "Data Change Error");
return;
}
}
However, VariantType is not a flags enum, so the 'And Not' operation is not producing a meaningful result in either language.
Going by the text in the message box, the correct condition would be VarType(ItemValues(i)) <> VariantType.Array
in VB, Information.VarType(ItemValues[i]) != VariantType.Array
.
Avoiding the VB 6 compatiblity functions, you could write if (!(ItemValues[i] is Array))
.
If you want to keep using the VB 6 compatiblity functions in C# to make porting easier, you need to add a reference to Microsoft.VisualBasic.dll.