Isaiah's Blog

A vbCity Leader's journal

vbCity Blogs moved to:
http://cs.vbcity.com/blogs
  Home :: Syndication  :: Login

AprMay 2013Jun
SMTWTFS
2829301234
567891011
12131415161718
19202122232425
2627282930311
2345678

Articles

Archives

Topics

Image Galleries

Blogs I Read

Tuesday, June 10, 2008 #

Summary: Provides an overview of generics, constraints and their implementation.

 

Generics in Visual Basics 2005 make it possible to re-use code and still have strong typing.  With Visual Basics 2003 a different collection had to be defined for each data-type causing repetition of code. Generics allows for classes and methods to facilitate unrelated types. A major benefit of Generics is that one collection can be created to handle all data-types needed, thus cutting the amount of code needed.

 

Using Object as the item for the collection is another way that one collection can handle all data-types needed. However, with the use of Object the performance would be adversely affected because the types would require casting and type validation. Whereas, with the use of Generics the collection is strongly typed for all data-types; meaning that there is automatic type validation and other processes are avoided that would affect performance. 

 

Defining Generic Types

 

A generic type is considered to be a complete generic class. When defining a generic class the Of keyword followed by a character(s) is added to class definition.

 

This is a definition of a regular class:


Public Class DemoClass

    ' Some methods and types here!

End Class

 

And now this is a definition of a generic class:


Public Class DemoClass(Of t)

    ' Some methods and types here!

End Class

 

Notice the difference between the regular class definition and the generic class definition. The generic class has the keyword Of followed by a t in parentheses at the end of the declaration line. The Of keyword is telling the compiler that there will be a type named “t” that will be filled in later. That type is defined by whatever is passed to it, when it is implemented. The character(s) that follows the Of keyword are known as a generic type parameter. Any combination of letters can be used, not just a single letter.  “t” would be considered the generic parameter in this case.

 

Using Generic Type Parameters

 

The use of generic types within methods allows the class to contain more flexible methods. The benefit of using these types within methods can clearly be seen through a strongly typed collection example.

 

Without the use of generics a simple add method within a collection would look like

 

Public Class DemoClass

    Inherits System.Collections.CollectionBase

 

    Public Function Add(ByVal value As Person) As Int32

        Me.InnerList.Add(value)

    End Function

End Class

 

However, with generics the collection is able to handle any type passed.

 

 Public Class GenericCollection(Of t)

    Inherits System.Collections.CollectionBase

   

    Public Function Add(ByVal value As t) As Int32

        Me.InnerList.Add(value)

    End Function

End Class

 

The amount of coding is cut due to the fact that one strongly typed collection can be created to handle all types needed. In the code example above the generic parameter is used as the type of the parameter for the Add function.

 

When defining the class for use a type must be passed to define the generic parameter, for that instance of the class.

 

Public Class DemoClass

    Public Sub RandomMethod()

        Dim gc As GenericCollection(Of Person)

    End Sub

End Class

 

Notice that the Person object has been used for the generic parameter in this case. In theory the code above creates a new instance of the GenericCollection class and passes the Person object as the generic parameter. What this means is that this instance of the GenericCollection is strongly typed for a Person object.

Creating Generic Methods

 

Creating generic methods is similar to the creation of a regular method.

This is a definition of a regular method.


Public Class DemoClass

    Public Sub RegularMethod()

        ' Some code goes here!

    End Sub

End Class


This is a definition of a generic method.

Public Class DemoClass

    Public Sub GenericMethod(Of t)()

        ' Some code goes here!

    End Sub

End Class

 

Generic methods can used to reduce the amount of code needed to complete several similar tasks. For example consider obtaining data from a database. One generic method can be written to handle all type within that database.

 

Public Function GetValues(Of t)(ByVal sql As String) As List(Of t)

    Dim cmd As New OleDbCommand(sql, connection)

    Dim reader As OleDbDataReader = cmd.ExecuteReader()

    Dim list As New List(Of t)

 

    While reader.Read()

        list.Add(CType(reader(0), t))

    End While

 

    Return list

End Function

 

Why use List(Of t) instead of CollectionBase?

 

When creating a new collection class List(Of t) should be used as the base class over CollectionBase. This is the case because CollectionBase is a non-generic class, and there is no efficient way to switch between non-generic and generic code. List(Of t) provides the full functionality of any give collection in generic form.

 

What if I want to limit generic types?

 

In several cases the generic type parameter needs to be limited to a specific type. Generic types need to be limited in these cases to ensure that the particular type can perform the task needed. These types are limited through the implementation of constraints. Considering a generic collection that contains a sort method, that generic type would have to be limited to types that implement the IComparable interface.


Public Class GenericCollection(Of t As IComparable(Of t))

    Inherits System.Collections.Generic.List(Of t)

    Public Sub New()

        ' Initialize a new instance of this object.

        MyBase.New()

    End Sub

End Class

 

Notice when the generic type is defined the constraint is also put into place. The constraint is defined by the use of the As keyword directly after the generic type parameter. It is important that the same character(s) be used in defining both the generic type parameter and the generic constraint.

 

IComparable is an interface that is implemented upon types that can be sorted. This interface defines a general method that tells the application how types should be compared. All collections can be sorted by a value within that collection. Notice that the code below does not implement the IComparable interface.

 

Public Class Person

    Private _firstName As String

    Private _lastName As String

 

    Public Property FirstName() As String

        Get

            Return _firstName

        End Get

        Set(ByVal value As String)

            _firstName = value

        End Set

    End Property

 

    Public Property LastName() As String

        Get

            Return _lastName

        End Get

        Set(ByVal value As String)

            _lastName = value

        End Set

    End Property

End Class

 

When the Person object, whose code is above, is used as the generic type for the GenericCollection class an error occurs.

 

Public Class DeomClass

    Public Sub DemoMethod()

        Dim gc As New GenericCollection(Of Person)

    End Sub

End Class

The error states that the Person object does not implement the IComparable interface. IComparable is used as a constraint to ensure that the type can be sorted. To correct the error simply implement the IComparable interface.

 

Public Class Person

    Implements IComparable(Of Person)

 

    ' The rest of the code for the object.

 

    Public Function CompareTo(ByVal other As Person) As Integer Implements System.IComparable(Of Person).CompareTo

 

    End Function

End Class

 

What if I need multiple constraints?

 

In some cases generic types need to be constrained by more than one constraint. Multiple constraints are defined just like single constraints with a small exception.

 

Public Class GenericCollection(Of t As {IComparable(Of t), New})

    Inherits System.Collections.Generic.List(Of t)

    Public Sub New()

        ' Initialize a new instance of this object.

        MyBase.New()

    End Sub

End Class

 

Notice that when defining multiple constraints they are enclosed in { } and separated by a comma.

 

Special Constraints

 

There are a few special constraints such as classes and new. These constraints are rather important to use because it ensures that the generic parameter has the capability to accomplish the task necessary. For instance when using a generic parameter that needs to be initialized, the constraint new needs to be used.

 

Public Class DemoClass(Of t As New)

    Public Function GetItem() As t

        Dim newType As New t

 

        ' Some more code here.

 

        Return newType

    End Function

End Class

 

The code above is used just to illustrate a purpose, and has no real functionality as it is. New is used as a constraint to ensure that the generic parameter has a default constructor to be called upon. Classes are used as constraints to check if the type inherits from that particular class. The use of classes as a constraint is a good idea because it ensures that the type will be able to perform the functions within the class.

 

Generics and constraints reduce the amount of work that the program used to have to do. In the past a programmer had to create several collections that all served the same purpose and perhaps had to spend a great deal of time debugging that code. Now with generics that headache has become a thing of the past.

posted @ 6:42 PM | Feedback (74)

Sunday, December 04, 2005 #

It has been along time since I have posted. It has been extremely busy since my last post with school and of course the friendly hurricane Katrina. I will post some pictures from Katrina when I finally get a chance.

I am glad to say that I am about to publish my first article. It has been an extremely long process. I have learned a great deal about how to write an article and what readers actually look for in an article. Oh well, enough with the boring details in a few days I will be publishing an article that introduces generic types in Visual Basic 2005. So keep your eyes on my blog for a link.

posted @ 1:33 AM

Monday, June 20, 2005 #

Steve Jobbs made the right move in my eyes, with the change to intel. I am tad bias on this matter, however, considering I am windows based developer. In the coming years I am sure that we will see MAC clones all over the market, thus making the MAC os cheaper and readily accessable for the average joe. With this in mind we will see a rise in MAC usage from the average person.

Although, this was the right move, I seriously doubt that it will impact Microsoft the way Jobbs intended. With the up coming release of Longhorn, I believe that Microsoft will continue out do Apple.

posted @ 7:54 AM

Friday, May 27, 2005 #

I have finally finished high school, and have made some time to start blogging again. It turns out that I will be attending the University of Alabama come this fall. I will be there for five weeks this summer as apart of an advanced math program.

I really don't have much to say today. Although, I just wanted to say that I am going to start again. So keep an eye out for new post. =)

posted @ 4:15 PM

Tuesday, March 01, 2005 #

Since the creation of the .Net Framework developers have been bickering over what language is better. Better is not the best word to use because there is a great deal of myths surrounding VB.Net in regards to its implementation.

I have read stories how several VB6 developers believe that in order to program in .Net it would require C#, VB.Net is only for web development, and that VB is going away. Well, just to set the record straight C#, VB.Net C++.Net, and J# can all be used in programming within .Net, VB.Net can be used in web development and in application development, and VB is not going away. 

With the coming release of VS.Net 2005 the public will see that C# supports a handful of new features that VB.Net doesn't support. From my stand point I believe that Microsoft is sticking true to what they have said all along. VB.Net and C# are both languages designed upon the .Net Framework, however, one will a few features the other doesn't. If the languages were the same it wouldn't make any since for Microsoft to maintain both languages.

My stance on the battle is that VB.Net is better of the two langauges. For me it all boils down to the fact I don't like visiting semi-colon land and the simple fact VB is much easier to read/work with than C#.

The battle continues ...

posted @ 6:59 AM

Monday, February 07, 2005 #

This entire week I am attending Presidential Classroom in Washington D.C. So far I can say that it is extremely interesting in what I have been able to ask and gain from others. However, the people that run this seem a tad over protective in that I cannot get on the internet with my PC. I have to use the George Town's eMacs. Presidential Classroom is where students get an introduction into the world of politics and how they affect an area of interest. My area of interest of course is Technology. From this week I hope to find out why the government is allowing the RIAA to do as they please and whats going on with the Microsoft lawsuits.
posted @ 6:20 AM

Friday, January 21, 2005 #

Ever since I was a young child I can remember singing the words “the home of the brave and the free.” Those words have come alive, in my life, from this week that I have spent in Washington D.C. At President Bush's inauguration He said that we will not allow tyranny rule and oppression; those words show that this nation is truly the home of the brave and the free.

The United States of America is truly the home of the free because of those hundreds of millions that have come before us that fought and died so that we may fuel our zeal of freedom. She is the home of the brave because she there is not a force in the world that she is afraid or worried about. The United States of American is truly a lighthouse of hope and freedom throughout this world. She shines brightly so that everyone under the sun may see the hope and freedom.

We, as American citizens, live in a nation that is founded upon the belief that freedom shall ring. That should not just ring in the hearts of Americans but that it should ring throughout the world.  

God bless the United States of American and freedom continue to resonate in the hearts of all.

posted @ 5:44 AM

Monday, January 10, 2005 #

Throughout previous versions of Visual Basic accomplishing the most simple task took several lines of code. My favorite example of how the My namespace has made life easier is with downloading files. In previous versions of VB.Net the developer had import the System.Net and several other namespaces. The following code is how one might obtain a text file from the internet without using the My namespace

Imports System.Net
Imports System.Net.Sockets

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

        Cursor = Cursors.WaitCursor

        '-- Create a new Socket for TCP/IP use
        ClientSocket = New Socket(AddressFamily.InterNetwork, _
           SocketType.Stream, ProtocolType.Tcp)
        '-- Create an endpoint to a server on port 80
        Dim EP As New _
        IPEndPoint(IPAddress.Parse("127.0.0.1"), 80) '127.0.0.1 is localhost
        '-- Connect to the Endpoint
        ClientSocket.Connect(EP)
        '-- Send an HTTP string to retrieve a document
        Dim SendThis() As Byte = _
          System.Text.ASCIIEncoding.ASCII.GetBytes("GET /sockets1.txt" & _
          vbCrLf) 'Change the file name
        ClientSocket.Send(SendThis)
        '-- Wait for received data
        Do
            '-- Is data available?
            If ClientSocket.Poll(1, SelectMode.SelectRead) = True Then
                '-- Available property returns number of bytes ready
                ' to be read. You must read into a byte array.
                ' This is because a character can be more than
                ' one byte if Unicode.
                Dim ReceiveThis(ClientSocket.Available) As Byte
                '-- Read the data
                ClientSocket.Receive(ReceiveThis)
                '-- Convert the byte array to an ASCII string
                TextBox1.Text = _
                  System.Text.ASCIIEncoding.ASCII.GetString(ReceiveThis)
                '-- All done!
                Exit Do
            Else
                '-- Allow other processes to occur
                Application.DoEvents()
                '-- Put the PC to sleep for 1 millisecond to avoid
                ' CPU overload
                System.Threading.Thread.Sleep(1)
            End If
        Loop
        '-- Shutdown and Close the socket. You must always do this
        ClientSocket.Shutdown(SocketShutdown.Both)
        ClientSocket.Close()

        Cursor = Cursors.Default
    End Sub

Roughly twenty-five lines, of actually, code can be condensed to one line. Please note that the code above only displays the text received in a text box. Whereas, the code below will actually download the file to your physical disk.

My.Computer.Network.DownloadFile(”http://127.0.0.1/VBRocks.txt”, “C:\My Documents\VBRocks.txt”)

My is one of several new features that we have to look forward to. What is your favorite feature of My?

posted @ 9:33 PM

Saturday, January 01, 2005 #

Slashdot | RIAA/MPAA Contractor Deploys Malicious Adware Trojans

Where do we draw the line of right and wrong? Apparently the RIAA/MPAA  believes that it is alright to take on the persona of a hacker. Within the United States these actions, however good the intentions, are illegal and carry a heavy punishment. This raises the question “what makes it alright for them to deploy trojans and not someone else?” Do not get wrong here, I am in no way saying that file piracy is right in form or fashion. I believe that software and music alike should be purchased. I am just making a point that I believe that the RIAA/MPAA should face the same punishments that any other hacker would have to face.

posted @ 11:30 AM

Friday, December 31, 2004 #

Have you ever wondered what it would be like to interview at Microsoft? Well, the Channel 9 team has interviewed Zoe Goldring and Gretchen Ledgard, both are technical recruiters for Microsoft. The clip ::  Zoe Goldring and Gretchen Ledgard - What is it like to interview at Microsoft?

According to the Technical Careers @ Microsoft blog it is “Be nice to a recruiter Month” (January 2005). :: Mark your calendars - Be Nice to a Recruiter Month is almost here! 

Lets all be nice to recruiters =)

posted @ 7:27 PM

Thursday, December 30, 2004 #

Google has done an amazing job with their new search. I got bored and decided that I would give it a whril by searching for news about vbCity and I found something about our blogs.

'Blogs' provide first-person, on-the-scene accounts of tsunami chaos

Blogs do provide first-person accounts for what has and is happening due to the tsunami. Shandy has posted several accounts of what it is like to leave through a tsunami which can be found at :: An Experience of Living Through A Tsunami

posted @ 3:50 PM

Wednesday, December 29, 2004 #

Theft On The Web: Prevent Session Hijacking I would suggest that all network developers and network administrators read over this article. It goes into detial of how hackers attack your network and the data.
posted @ 6:00 PM

Today I was listening to several presentations on Whidbey and the new features that Microsoft has added. These additions were taken straight from customer feedback which has made this an execellent product. However, are we asking for a language that is too high level based.

I have been wondering for some time now what would be my response if I were asked “Do you think that Microsoft has made Visual Basic too high level?” My response to these is rather simple - I believe that Microsoft has developed a language that is at several different levels. What I mean is that there are all these fancy controls and namespaces such as My, however, these additions were added to help bring back RAD and make learning easier for beginners and those programmers that are moving from VB6.

The beautiful thing about .Net is that it can have all these namespaces and controls but the programmer doesn't have to use them. The programmer can still developed their own controls and namespace and move a way from the idea of high level.

How high is too high for Visual Basic?

posted @ 5:56 PM

Thursday, November 04, 2004 #

There was one point in time in which I thought that it would be rather easy for me to decide on a college. Well, now that they time is upon me I am finding that it is a harder process than I originally thought. The good news is that I have it narrowed down to three different schools. Oral Roberts University, University of Southern Mississippi and University of Virginia are the three schools that I am looking at, each of them have something different to offer but the end result is the same an education. Also, through this process of looking for a school I have found that there is a good deal more math involved with a Computer Science degree.

The hard part is not picking a place I rather be or an education that I would like to have but the best school for me. 

 

posted @ 6:59 AM

Sunday, August 22, 2004 #

Having programmed in Visual Basic for a little over three years gives me a keen eye for the holes in others and likewise the holes in Visual Basic. I believe that each language is designed with a single purpose in mind and each language is catered to that purpose.

In school I am taking AP Computer Science and the curriculum is java programming. After the first few days I began to think that the people who designed java got half way through and just decided to throw in the towel. Having completed the second week of that class I am starting to think that java has too many holes to be used for anything.

This is where Visual Basic .Net 2005 comes into the picture. If I am going to have to use a language I want it to have some of the basic features. Java is lacking several different minor features. So I took the liberty of writing a for-each loop in Visual Basic .Net 2005.

Public Class VBforeach(Of c As {CollectionBase, New}, t)

 

    Public Delegate Sub foreachd(ByVal colType As t)

 

    Public Sub New()

        MyBase.New()

    End Sub

 

    Public Sub foreach(ByVal collection As c, ByVal colType As t)

        Dim handler As foreachd = AddressOf DelegateAction

        For Each colType In collection

            handler.Invoke(colType)

        Next

    End Sub

 

    Public Overridable Sub DelegateAction(ByVal colType As t)

        ' If this prints then there is not overrides

        System.Console.WriteLine("Hello, World")

        System.Console.ReadLine()

    End Sub

 

End Class

 

Now I know there is a select few people out there saying that this just some VB programmer ranting. After all this code can only run on a Windows based pc that has .Net Framework 2.0 installed. In all honsety this can be done in any other language so there is no point in getting angry about this.

 

This is just the beginning ...

posted @ 1:25 PM