HELP: GetSqlBinary conversion in C# and VB.NET

  • Thread starter Thread starter Gareth Parris
  • Start date Start date
G

Gareth Parris

Anyone know what the VB.NET equivalent of this C# statement is...

byte [] segBody = (byte []) sqlReader.GetSqlBinary(3);

Tried as hard as I could to do it in VB.NET but I cannot seem to do it.
 
Gareth Parris said:
Anyone know what the VB.NET equivalent of this C# statement is...

byte [] segBody = (byte []) sqlReader.GetSqlBinary(3);

Tried as hard as I could to do it in VB.NET but I cannot seem to do
it.

Untested:
dim segbody as byte() = directcast(sqlReader.GetSqlBinary(3), byte())
 
Hi Gareth,

|| byte [] segBody = (byte []) sqlReader.GetSqlBinary(3);

GetSqlBinary returns a SqlBinary structure rather than an array of bytes,
so a straight conversion to VB fails, as you have found. Does that C#
statement actually work?

These fail:
Dim segBody1 As Byte() _
= DirectCast (sqlReader.GetSqlBinary(3), Byte()) 'Fails
Dim segBody2 As Byte() _
= CType (sqlReader.GetSqlBinary(3), Byte()) 'Fails

See if this code [untested] gives you some joy:
(Imports System.Data.SqlTypes)
Dim sqlBinValue As SqlBinary = sqlReader.GetSqlBinary(3)
Dim segBody As Byte() = SqlBinary.op_Explicit (sqlBinValue)

Regards,
Fergus
 
Thanks Fergus. Funnily enough the C# code works perfectly. I'll try your VB
example right now.

Cheers,
Gareth
 
Fergus. Excellant stuff that worked nicely!

Gareth Parris said:
Thanks Fergus. Funnily enough the C# code works perfectly. I'll try your VB
example right now.

Cheers,
Gareth

Fergus Cooney said:
Hi Gareth,

|| byte [] segBody = (byte []) sqlReader.GetSqlBinary(3);

GetSqlBinary returns a SqlBinary structure rather than an array of bytes,
so a straight conversion to VB fails, as you have found. Does that C#
statement actually work?

These fail:
Dim segBody1 As Byte() _
= DirectCast (sqlReader.GetSqlBinary(3), Byte()) 'Fails
Dim segBody2 As Byte() _
= CType (sqlReader.GetSqlBinary(3), Byte()) 'Fails

See if this code [untested] gives you some joy:
(Imports System.Data.SqlTypes)
Dim sqlBinValue As SqlBinary = sqlReader.GetSqlBinary(3)
Dim segBody As Byte() = SqlBinary.op_Explicit (sqlBinValue)

Regards,
Fergus
 
Hi Gareth,

That op_ Explicit was niggling away in my mind and I've just remembered.

C# provides the ability to define explicit conversions which take place
when a variable is cast from one form to another. op_Explicit is the function
that allows other languages to access that convesion.

So
(byte []) sqlReader.GetSqlBinary(3);
and
SqlBinary.op_Explicit (sqlReader.GetSqlBinary(3));
are equivalent.

Regards,
Fergus
 
Back
Top