473,544 Members | 1,594 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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(this Cl, BaseCl).baseClM ethod ... ?
--
Cheers,
Crirus

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

------------------------------
Nov 20 '05 #1
13 1886
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****@datagro up.ro> wrote in message
news:%2******** ********@TK2MSF TNGP12.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(this Cl, BaseCl).baseClM ethod ... ?
--
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.o rg> wrote in message
news:%2******** ********@TK2MSF TNGP10.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****@datagro up.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.Visua lBasic.Compiler Services.String Type::FromObjec t)

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

Admittedly, the first thing
Microsoft.Visua lBasic.Compiler Services.String Type::FromObjec t 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*******@free net.de> wrote in message
news:OF******** ******@TK2MSFTN GP11.phx.gbl...
"Crirus" <Cr****@datagro up.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*********@ho tmail.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 WindowsApplicat ion280.Form1
IL_0008: stloc.0

IL_0009: ldloc.1
IL_000a: castclass WindowsApplicat ion280.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*********@ho tmail.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*******@free net.de> wrote in message
news:Oc******** *****@tk2msftng p13.phx.gbl...
"Trev Hunter" <hu*********@ho tmail.com> schrieb

Just my 2 worthless euro cents ;)


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

Nov 20 '05 #10

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

Similar topics

10
8716
by: Sahil Malik | last post by:
I can't find it .. what am I missing? - Sahil Malik http://dotnetjunkies.com/weblog/sahilmalik
4
7259
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) Thanks, Andreas
11
7746
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 reflection and get the type from there and then cast it to that type so i can use it. When i use DirectCast, it won't let me do something like...
6
10816
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 found this in the VB Language reference: <quote> The DirectCast keyword introduces a type conversion operation. You use it the same way you use the...
5
5051
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
2113
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: Specified cast is not valid. In general terms the code is constructed as follows; ModuleA Public xlWb As Excel.Workbook
7
2707
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
4094
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 convert it -- -iwdu15
3
2182
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 named 'StandardWebsiteUserRoleID'... Public ReadOnly Property StandardWebsiteUserRoleID() As Integer Get Return...
0
7424
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7365
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
7772
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
0
7709
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
1
5297
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
4918
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3415
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
0
3409
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
988
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.