Directcast

DekaFlash

Well-known member
Joined
Feb 14, 2006
Messages
117
Programming Experience
1-3
How do I directcast the following line please?

DataGrid1.Cells(1, k).Font = New System.Drawing.Font("Tahoma", 11.0!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.World, CType(0, Byte))

Thanks
 
Well I have been running my code through a optimizer and on lines like

DataGrid1.Cells(1, k).Font = New System.Drawing.Font("Tahoma", 11.0!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.World, CType(0, Byte))

It suggests that Ctype is slower then Directcast.

I am relatively new to VB.NET 2003 and am unfamiliar with the difference between ctype and directcast.

I am presuming the ctype part of the line, but I am unsure how or even if it is possible to directcast it.

Thanks
 
Well, when the option Strict is on, casting is strict and not automatic. So you suppose to do it (explicit casting) with the cast operator CType() or DirectCast. Below is an example that i hope will clarify casting to you ;)
VB.NET:
textbox = CType(object, TextBox)
textbox = DirectCast(object, TextBox)

Regards ;)
 
Given that Byte is a value type and you are passing zero you don't need to cast anything. You can do this:
VB.NET:
[SIZE=2]DataGrid1.Cells(1, k).Font = [/SIZE][SIZE=2][COLOR=#0000ff]New[/COLOR][/SIZE][SIZE=2] System.Drawing.Font("Tahoma", 11.0!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.World, [/SIZE][SIZE=2][COLOR=#0000ff]New[/COLOR][/SIZE][SIZE=2][COLOR=#0000ff] Byte[/COLOR][/SIZE][SIZE=2])[/SIZE]
The default value is zero so it has the desired result. That might save another half a nanosecond. :)

Note that the difference between CType and DirectCast is that CType does additional type checking. CType works if there is a valid conversion between the two types while DirectCast works only if the run time types are the same, i.e. the type being cast to is derived from the type being cast from or vice versa.
 
Back
Top