VB Ctype equivalent to C#

254 Views Asked by At
ServerInfo = CType(System.Runtime.InteropServices.Marshal.PtrToStructure(BufferPtr, GetType(SERVER_INFO_100)), SERVER_INFO_100)

I need to convert this CType to C#. I am not aware on VB.net. Please suggest how to do this and also forloop

For index = 0 To iEntriesRead - 1
2

There are 2 best solutions below

4
Amit Verma On

you can use "as" in C# for casting

For eg:

ServerInfo = Marshal.PtrToStructure(BufferPtr, typeof(SERVER_INFO_100)) as SERVER_INFO_100;

For the For loop in C# you can follow below code

for(int index=0;index< iEntriesRead - 1;index++)
{
  //your code
}
1
Tim Schmelter On

CType is a cast operator/function, so comparable to (SERVER_INFO_100) object in C#.

ServerInfo = (SERVER_INFO_100) System.Runtime.InteropServices.Marshal.PtrToStructure(BufferPtr, GetType(SERVER_INFO_100));

The closest you get to the C# cast operator is DirectCast in VB.NET. Read: Difference between DirectCast() and CType() in VB.NET

In C# you could also use the as cast operator which is the same as the VB.NET TryCast.

ServerInfo = System.Runtime.InteropServices.Marshal.PtrToStructure(BufferPtr, GetType(SERVER_INFO_100)) as SERVER_INFO_100;

This has the advantage that you don't get an exception if the type is not SERVER_INFO_100.

Please suggest how to do this and also forloop

The for-loop is explained in the docs.