469,273 Members | 1,769 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,273 developers. It's quick & easy.

directcast

can anyone explain the directcast code...ive tried using it and lookin it up
but im lookin for an easy definition and how it works...ive tried using it
before byut it throws errors saying it can convert it
--
-iwdu15
Nov 21 '05 #1
1 3907
You can use Directcast to convert objects to their actual type...it cannot be
used to convert to types other than the underlying type of an object. For
example;

Public Class myClass
.....
Public ReadOnly Property Length() as single
Get
Return 25.6
End get
End Property
End Class

Dim myArrayList as new ArrayList
Dim myClassInstance as New myClass
myArrayList.Add(myClassInstance) .

You could use Directcast as follows:

Dim lgth as Single = DirectCast(myArrayList(0), myClass).Length

or a simpler example:

Dim obj as Object
dim i as Integer = 25
obj = i

Dim j as integer = DirectCast(obj, Integer) 'Works to convert obj to an
Integer
dim j as integer = Ctype(obj, Integer) 'Works to convert obj to an Integer
Dim j as Double = DirectCast(obj, Double) 'Doesn't work because the
underlyng type of obj is not a Double.
Dim j as Double = Ctype(obj, Double) 'Works because the underlying obj type
of integer can be converted to a double.

You should use Directcast when possible to convert objects to their
underlying types instead of Ctype because it is faster. You could also use
Option Explicit OFF to avoid either DirectCast or Ctype by using late binding
but this is much slower and is more prone to allowing hard to detect errors
to be introduced into your procedures.

In VB.Net 2005, a lot of DirectCasts will not be required becasue of the
implemetation of "Generics".

Hope this helps
Dennis in Houston

"iwdu15" wrote:
can anyone explain the directcast code...ive tried using it and lookin it up
but im lookin for an easy definition and how it works...ive tried using it
before byut it throws errors saying it can convert it
--
-iwdu15

Nov 21 '05 #2

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

10 posts views Thread by Sahil Malik | last post: by
11 posts views Thread by Tubs | last post: by
13 posts views Thread by Crirus | last post: by
6 posts views Thread by Ot | last post: by
6 posts views Thread by Mark Nethercott | last post: by
7 posts views Thread by Brian Henry | last post: by
3 posts views Thread by =?Utf-8?B?TWlrZQ==?= | last post: by
1 post views Thread by CARIGAR | last post: by
reply views Thread by zhoujie | last post: by
reply views Thread by suresh191 | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.