Non-Type Safe Example

  • Thread starter Thread starter Jeff Chan
  • Start date Start date
J

Jeff Chan

I have read the documentation from msdn to try to understanding the concept
of "Type safe". Would someone give me an example of code segment
illustrating what is *Non* type safe?

Many Thanks,
Jeff.
 
Jeff Chan said:
I have read the documentation from msdn to try to understanding the concept
of "Type safe". Would someone give me an example of code segment
illustrating what is *Non* type safe?

It's hard since you can't write unsafe code in VB, and VB has always been
Type Safe. You can write terrible code with dozens of hidden
InvalidCastExceptions and NullReferenceExceptions, but you can't violate the
type system. To be Type Safe is to obey the type system, to access memory
only through the methods of declared types.

In the beginning, programs viewed their memory as an undifferentiated extent
of bytes. Then C added types and structs to give names to the bits. But in
C you can always directly access any area of memory, and the compiler will
allow almost any assignment. This direct memory access causes both
dangerous bugs and vectors for malicous code. For instance a "buffer
overrun" is a simple programming error in a non type-safe language which can
be exploited by a malicous client.

VB is verifiably Type Safe. This means that a VB program simply cannot have
a buffer overrun or a memory leak. A VB program cannot generate an access
violation, or touch any area of memory it isn't supposed to. And you can
verify all this at runtime, so you don't have to trust the programmer to use
the right compiler switches or to not make mistakes.

David
 
Hi Jeff,

Here is an example:

Dim notTypeSafeCollection As New Collection()
notTypeSafeCollection.Add("John")

notTypeSafeCollection.Add(1)

notTypeSafeCollection.Add(New Object())

Notice that I can add any object to the collection. If I decided to use it to store account objects I could accidently store a non-account object in the collection. The collection is not type safe.

and here is a link to an article on how to create a type safe collection:

http://www.devcity.net/Articles/66/1/typesafe_collection.aspx


--
Mike

Mike McIntyre
Visual Basic MVP
www.getdotnetcode.com
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top