473,289 Members | 1,875 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,289 software developers and data experts.

directCast

Can I use DirectCast to convert a object to it's base or should I use CType?
I have a instance of a class as Object.
The run-time tipe is a derived of a class, but I need to refer to that
instance as to the base class

Ex: Class BaseCl
Class DerivCl
Inherits BaseCl

'Run-time
Dim thisCl as Object= new DerivCl
Can I use DirectCast(thisCl, BaseCl).baseClMethod ... ?
--
Cheers,
Crirus

------------------------------
If work were a good thing, the boss would take it all from you

------------------------------
Nov 20 '05 #1
13 1871
AFAIK, yes.

CType does a *conversion* from one type to another (e.g. Integer to a
string)

DirectCast simply takes an object, and casts it to a derived or base or
interface type. For directcast to work, there must be a direct relationship
between the types. In your example, because "thisCl" contains "DerivC1" and
"DeriveC1" inherits from "BaseC1", there is a direct relationship.

HTH,

Trev.

"Crirus" <Cr****@datagroup.ro> wrote in message
news:%2****************@TK2MSFTNGP12.phx.gbl...
Can I use DirectCast to convert a object to it's base or should I use CType? I have a instance of a class as Object.
The run-time tipe is a derived of a class, but I need to refer to that
instance as to the base class

Ex: Class BaseCl
Class DerivCl
Inherits BaseCl

'Run-time
Dim thisCl as Object= new DerivCl
Can I use DirectCast(thisCl, BaseCl).baseClMethod ... ?
--
Cheers,
Crirus

------------------------------
If work were a good thing, the boss would take it all from you

------------------------------

Nov 20 '05 #2
Can I use DirectCast to convert a object to it's base or should I use CType?


It doesn't matter which one you use in this context.

Mattias

--
Mattias Sjögren [MVP] mattias @ mvps.org
http://www.msjogren.net/dotnet/ | http://www.dotnetinterop.com
Please reply only to the newsgroup.
Nov 20 '05 #3
I gues it does for speed sake

--
Cheers,
Crirus

------------------------------
If work were a good thing, the boss would take it all from you

------------------------------

"Mattias Sjögren" <ma********************@mvps.org> wrote in message
news:%2****************@TK2MSFTNGP10.phx.gbl...
Can I use DirectCast to convert a object to it's base or should I use
CType?
It doesn't matter which one you use in this context.

Mattias

--
Mattias Sjögren [MVP] mattias @ mvps.org
http://www.msjogren.net/dotnet/ | http://www.dotnetinterop.com
Please reply only to the newsgroup.

Nov 20 '05 #4
"Crirus" <Cr****@datagroup.ro> schrieb
I gues it does for speed sake


Nope. If CType casts (not converts) it does *exactly* the same.
--
Armin

http://www.plig.net/nnq/nquote.html
http://www.netmeister.org/news/learn2quote.html

Nov 20 '05 #5
Not in all cases.

Have the look at the IL for the following code (when compiled in release
mode):

-----------------
Sub Main()

Dim b As String = "hello"
Dim a As Object = b
Dim c As String

c = CType(a, String) ' Method 1
c = DirectCast(a, String) ' Method 2
c = CStr(a) ' Method 3

End Sub
------------
Both Method 1 and Method 3 do the same thing (a call to
Microsoft.VisualBasic.CompilerServices.StringType: :FromObject)

Method 2 (directcast) uses the "castclass" instruction directly.

Admittedly, the first thing
Microsoft.VisualBasic.CompilerServices.StringType: :FromObject seems to do is
check if it is already a string type and then call "castclass" and return,
but there is still a small overhead in calling the extra function in the
first place.

Not that optimizations like this will make much difference unless involved
in a mad loop of some sort. Still, I think it is better for the developer to
know the difference between when they *can* use directcast and when they
*have* to use ctype.

HTH,

Trev.
"Armin Zingler" <az*******@freenet.de> wrote in message
news:OF**************@TK2MSFTNGP11.phx.gbl...
"Crirus" <Cr****@datagroup.ro> schrieb
I gues it does for speed sake


Nope. If CType casts (not converts) it does *exactly* the same.
--
Armin

http://www.plig.net/nnq/nquote.html
http://www.netmeister.org/news/learn2quote.html

Nov 20 '05 #6
"Trev Hunter" <hu*********@hotmail.com> schrieb
Not in all cases.


I thought it was clear that my answer is based upon the usage of the
keywords in the same situation:

In a Form:
Dim o As Object, f As Form1
o = Me
f = CType(o, Form1)
f = DirectCast(o, Form1)

The casts compile to:

IL_0002: ldloc.1
IL_0003: castclass WindowsApplication280.Form1
IL_0008: stloc.0

IL_0009: ldloc.1
IL_000a: castclass WindowsApplication280.Form1
IL_000f: stloc.0
Of course, you are right, this is not true in all cases. So, I should have
added: If it's unambigous at compile time that it will be a cast, not a
conversion, the result is the same.

--
Armin

http://www.plig.net/nnq/nquote.html
http://www.netmeister.org/news/learn2quote.html

Nov 20 '05 #7
> If it's unambigous at compile time that it will be a cast, not a
conversion, the result is the same.


I agree. It's nice to know that the VB compiler is smart enough in these situations. I still think it's important for developers to use directcast whenever possible if for the only reason that it makes them more aware of the type conversions / castings that are taking place. IME, there are too many VB programmers out there that have taken too much advantage of the late binding, variant, option strict off nature of previous VB versions.

Just my 2 worthless euro cents ;)

Trev.

Nov 20 '05 #8
"Trev Hunter" <hu*********@hotmail.com> schrieb

Just my 2 worthless euro cents ;)


Never had as much worth as now. :)
--
Armin

Nov 20 '05 #9
> Never had as much worth as now. :)

lol. Yeah I hope their worth goes up quite a bit in the next month - I'm
moving to Canadian cents soon - the more they're worth at the beginning of
March, the better ;)

Trev.

"Armin Zingler" <az*******@freenet.de> wrote in message
news:Oc*************@tk2msftngp13.phx.gbl...
"Trev Hunter" <hu*********@hotmail.com> schrieb

Just my 2 worthless euro cents ;)


Never had as much worth as now. :)
--
Armin

Nov 20 '05 #10
"Trev Hunter" <hu*********@hotmail.com> schrieb
Never had as much worth as now. :)


lol. Yeah I hope their worth goes up quite a bit in the next month -
I'm moving to Canadian cents soon - the more they're worth at the
beginning of March, the better ;)


Get you a German car before moving! It's getting expensive over there. ;-)
--
Armin

Nov 20 '05 #11
> Get you a German car before moving! It's getting expensive over there. ;)

Lol! Definetly - no way am I gonna drive one of those floaty yank tanks
everybody loves over there - would rather get a mountain bike and ride it in
the -30 degree weather :S

I've heard it's getting expensive, but it has to be better than the rip-off
country that Ireland has become in the last few years. Thanks god my last
few pay cheques have been in British sterling over the last while ;)

Trev

"Armin Zingler" <az*******@freenet.de> wrote in message
news:e4**************@TK2MSFTNGP12.phx.gbl...
"Trev Hunter" <hu*********@hotmail.com> schrieb
Never had as much worth as now. :)
lol. Yeah I hope their worth goes up quite a bit in the next month -
I'm moving to Canadian cents soon - the more they're worth at the
beginning of March, the better ;)


Get you a German car before moving! It's getting expensive over there.

;-)

--
Armin

Nov 20 '05 #12
When you are inheriting from a base class, the methods of the base class
can automatically be obtained through the Me keyword -

Me.bclMethod()

CType("thisCl",BaseCl) will work as well returning an object of type
BaseCl.

with regards,
J.V.Ravichandran
- http://www.geocities.com/
jvravichandran
- http://www.411asp.net/func/search?
qry=Ravichandran+J.V.&cob=aspnetpro
- http://www.southasianoutlook.com
- http://www.MSDNAA.Net
- http://www.csharphelp.com
- http://www.poetry.com/Publications/
display.asp?ID=P3966388&BN=999&PN=2
- Or, just search on "J.V.Ravichandran"
at http://www.Google.com

*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!
Nov 20 '05 #13
"Trev Hunter" <hu*********@hotmail.com> schrieb
Get you a German car before moving! It's getting expensive over
there. ;)


Lol! Definetly - no way am I gonna drive one of those floaty yank
tanks everybody loves over there - would rather get a mountain bike
and ride it in the -30 degree weather :S

I've heard it's getting expensive, but it has to be better than the
rip-off country that Ireland has become in the last few years. Thanks
god my last few pay cheques have been in British sterling over the
last while ;)

Trev


:-))
--
Armin

Nov 20 '05 #14

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

10
by: Sahil Malik | last post by:
I can't find it .. what am I missing? - Sahil Malik http://dotnetjunkies.com/weblog/sahilmalik
4
by: Andreas Klemt | last post by:
Hello, what has the better performance and what are you using? Dim myObj As Object = 70 a) Dim myInt As Integer = DirectCast(myObj, Integer) b) Dim myInt As Integer = Convert.ToInt32(myObj) ...
11
by: Tubs | last post by:
i am attempting to write something which can morph itself to whatever comes in and get the value property from it but i don't know what type it is until runtime. I am therefore trying to use...
6
by: Ot | last post by:
I apparently have a bit to learn about Casting and Conversion. I have been thinking of them as the same but a discussion in another thread leads me to believe that this is wrong thinking. I...
5
by: Michael Ramey | last post by:
Hello, There are quite a few ways to convert one object, say an integer to a string. Dim myStr as string dim myInt as integer = 123 myStr = cstr(myInt) myStr = myInt.toString()
6
by: Mark Nethercott | last post by:
I get the following failure when trying to access the builtin properties; An unhandled exception of type 'System.InvalidCastException' occurred in resultsoutput.dll Additional information:...
7
by: Brian Henry | last post by:
is there any speed diffrences between doing Ctype or directcast? I know about the inherite diffrences, but process usage time wise, does one take up more cycles then the other? thanks
1
by: iwdu15 | last post by:
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...
3
by: =?Utf-8?B?TWlrZQ==?= | last post by:
If Visual Studio knows the type, why does the system-generated property use CType instead of DirectCast? DirectCast is more efficient right? For example - Here's what we have for a setting...
2
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 7 Feb 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:30 (7.30PM). In this month's session, the creator of the excellent VBE...
0
by: MeoLessi9 | last post by:
I have VirtualBox installed on Windows 11 and now I would like to install Kali on a virtual machine. However, on the official website, I see two options: "Installer images" and "Virtual machines"....
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: Aftab Ahmad | last post by:
Hello Experts! I have written a code in MS Access for a cmd called "WhatsApp Message" to open WhatsApp using that very code but the problem is that it gives a popup message everytime I clicked on...
0
by: Aftab Ahmad | last post by:
So, I have written a code for a cmd called "Send WhatsApp Message" to open and send WhatsApp messaage. The code is given below. Dim IE As Object Set IE =...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: marcoviolo | last post by:
Dear all, I would like to implement on my worksheet an vlookup dynamic , that consider a change of pivot excel via win32com, from an external excel (without open it) and save the new file into a...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.