Cheat Sheet - Casting in VB.NET and C#

Describes several casting and type related operations in VB.NET and C#.

Introduction

This article describes several casting and type related operations in VB.NET and C#.

Casting in VB.NET

By default in VB, casting is automatically done for you when you assign objects to variables. The objects are then automatically casted to the variables' type.

This behaviour can be influenced by an option line on top of your code file:

OptionStrictOnOptionStrictOff

When on, casting is strict and not automatic.

Explicit casting can be done with the cast operator CType() or DirectCast():

textbox = CType(obj, TextBox)
textbox = DirectCast(obj, TextBox)

The difference between the two keywords is that CType succeeds as long as there is a valid conversion defined between the expression and the type, whereas DirectCast requires the run-time type of an object variable to be the same as the specified type. If the specified type and the run-time type of the expression are the same, however, the run-time performance of DirectCast is better than that of CType. DirectCast throws an InvalidCastException error if the argument types do not match.

Testing if an object is of a particular type, can be done with the TypeOf...Is operator:

IfTypeOf obj Is TextBox Then...

Obtaining a System.Type object for a given type can be done with the GetType operator:

Dim t As System.Type
t = GetType(String)
MessageBox.Show(t.FullName)

Obtaining a System.Type object for a given object can be done with the GetType method:

Please answer:
Is there a way to Convert variable with type as a String parameter?
Can you write a function like this:
a = MyTryCast(variable as Object, SystemType As String)
and then use it like:
a = MyTryCast("12.13", "System.Decimal")

I have a problem in my code with regard casting. I have a base class object called BaseDAO, a subclass is created from this called CustomerRowSet. I have a function which, through reflection, will create an instance of the subclass.

If the specified type and the run-time type of the expression are the same, however, the run-time performance of DirectCast is better than that of CType.
So which function gives the best performance under all circumstances? Can you give an example of what type of conversions cause DirectCast to throw!

You seem to have missed my point. I will try to explain myself better.

Obviously using C# requires casting. But that is because most of the framework is not designed as well as it could be. My point is about design not about the way the framework happens to be setup

Most of the time we only cast because C# doesn't allow us to make specialized collections easily enough yet. 'generics' will solve that hopefully.

No plugin architecture ever needs casting. Any plugin object inherits some interface. Obviously a give program only knows about the interface. If you end up casting using plugin objects your interfaces need redesigning

Concerning your good OO design (btw, I don't know if C++ purists are by definition to be considered as OO purists, but please, let's not start that discussion here... ):

Casting is in my opinion not a matter of design. Casting originates from the fact that the implementation is done in a strong-typed language. Would you implement in a purely object-oriented language as SmallTalk, then you would never have to cast, since it does no typechecking, and even does not know what casting is...

Now, should you design in such a way that casting will not be necessary in an implementation language ? My answer would again be no. Good OO designs are caracterised by their good distribution of responsibilities. Is it a good distribution of responsibility to have the superclass know about all it's (current but also future !?!) subclasses, since it should provide GetAsSubclass methods for each one of them ? I believe the contrary. By the way, as I pointed out, you can only provide GetAs methods for known (=current) subclasses, so you disallow extension by subclassing by 3rd parties. Wasn't OO meant to be extended that way ?

Consequently, if C# requires casting, it's not due to bad design (although design could have been better), but due to it's strong-typed character.

I think you have got mixed up here You do not need casting with a strongly typed language. That is the point of types. C# requires casting so frequently because of the bad design of the collections.

Rudi Breedenraedt wrote:I believe the contrary

I agree it is bad design to have GetAsSubclass method However that is a better solution than casting. This problem can be solved by good design. For example GetElementsByTagName in the XML part of the framework should return a list of XmlElements, not a list of XmlNodes as it currently does.

I don't really want to say this again but I will: in good design you do not need to downcast because the type of the object you are dealing with should already be the correct interface. That is basic OO programming using types and I refuse to discuss it anymore. Please have mercy

If you don't want to discuss it, and you can keep yourself from replying, don't reply.

otherwise:

dog_spawn wrote:I assume you already know that

lets, for this discussion, assume I don't.

dog_spawn wrote:in good design you do not need to downcast because the type of the object you are dealing with should already be the correct interface

This propagates requirement of knowledge of this interface through large parts of the project, In my experience, tight coupling is always the downfall of large projects, so I tend to reduce the coupling to the absolute minimum.

Do you accept the "virtue" of QueryInterface - or is this "wrong" too?

dog_spawn wrote:That is basic OO programming using types

OO is no religion, just a set of rules that have reasons. In programming, I refuse to accept a rule when noone can tell me the reason.

peterchen wrote:This propagates requirement of knowledge of this interface through large parts of the project, In my experience, tight coupling is always the downfall of large projects, so I tend to reduce the coupling to the absolute minimum.

Sorry, but that is insane. If you are saying pass only Object around that is just madness. You have to know the interface anyway as you have to cast it.