Scorpion Posted March 13, 2013 Share Posted March 13, 2013 (edited) I've tried googling but can not think on how to describe it to get the results i want. My Program will be having a lot of variables in it (mostly Arrays) but i remember doing a look time ago being able to create my own sub that had variables in it. then i could just declare that one variable on the form for the array rather than like 10 variables with arrays. Dim Details(20) As MyOwnFunction inside MyOwnFunction Dim Name As String Dim Phone As String Dim Text As String And So On Then asking for it i can just do Details(1).Name = textbox1.text.toString Thats how i would want to do it but cant find the code for the first bit. I dont want to declare Dim Name(20) As String Dim Phone(20) As String And so on Hopefully this makes sense and you can understand what im trying to do, plus why i couldnt think how to ask this in to google. Please help me :) Edited March 13, 2013 by Scorpion Quote Link to comment Share on other sites More sharing options...
ApacheTech Consultancy Posted March 13, 2013 Share Posted March 13, 2013 What you're after is Strongly Typed Collections. I wrote a blog about this on my Uni course page. I'll post it here for you to give the basics. Sorry if it seems a bit pedantic, it as written for very new programmers.AssumptionsI have made a few assumptions during this post: The reader understands VB.NET syntax Examples are given as a bare-bones demonstration only and any implementation will incorporate Defense Programming into it's design. Option Explicit in VB.NET is turned On Option Strict in VB.NET is turned On The reader understands that although this post is written using VB.NET syntax as an example language, the concept and implementation of OOP can be used in most modern high-level programming languages. OverviewOOP is a brilliantly elegant way of coding that is both easier for onlookers to understand and far more extendible than procedural programming. Procedural programming relies on things being done in order. A followed by B followed by C and so on; if you need to add something in between A and B once the program is stable, it involves redirecting the program from A to the new B and then to the old B, now C and everything moves along one in order. This isn't the way with OOP, you can add new Properties to an Object and everything you have done previously with it will be largely unaffected.An Object, in programming terms can be pretty much anything. In this article I'm going to stick with the all too familiar Student/Class/Tutor schema that seems to work quite well in textbooks. In every class, we sign a register. In programming terms, the Register is simply an Object. It contains within it a few Public Properties such as Tutor, Unit, Course, Students and so on. In this example, Students is Strongly Typed Collection of Student Objects. I will go into Strongly Typed Collection in another post, as it is another topic entirely. Each Student will have properties such as Name, DOB, SID, ContactDetails and so on.Creating ObjectsTo create an Object, you create a class, within a namespace, with the name of the Object you want to create. Option Explicit On Option Strict On Namespace MMU Class Student End Class End Namespace RegionsNext, we add the regions we're going to build on. There are four basic regions we will use: Private Members, Constructors, Public Properties and Public Methods. We only add these regions to aid our extensibility. It makes the object easier to read, and therefore upgrade when needed.There are other useful Regions to add to more complex objects, such as Events, Delegates, Destructors, Interfaces, Enums, et al, but for this example, the basic four will suffice. Option Explicit On Option Strict On Namespace MMU Class Student #Region "Private Members" #End Region #Region "Constructors" #End Region #Region "Public Properties" #End Region #Region "Public Methods" #End Region End Class End Namespace Private MembersThese are the local scope variables that are used within the Object. Within OOP, these variables hold the data once the Object is constructed and pass the data to the Properties to be outputted. This way, the local variables are never exposed to the public; they can be manipulated within the class as normal.Here, I have used a simple model of Student Number, Name and Course. In real world examples, this would be a much more extensive list. #Region "Private Members" Private m_sid As String Private m_firstName As String Private m_lastName As String Private m_course As String #End Region ConstructorsThe constructors are an essential point of any object. They are known as "Entry Points" to the Object and will tell the class how it gets the data for the object and how to store it once it's there.Here, I've overloaded the New sub procedure twice with different options to create a new student. This gives more flexibility to the program, and therefore the user to input data. It will check the number of string arguments and load the correct New Sub. #Region "Constructors" Sub New(ByVal _sid As String, ByVal _firstName As String, ByVal _lastName As String, ByVal _course As String) m_sid=_sid m_firstName=_firstName m_lastName=_lastName m_course=_course End Sub Sub New(ByVal _sid As String, ByVal _fullName As String, ByVal _course As String) m_sid=_sid m_firstName=_fullName.Split(CChar(" "))(0) m_lastName=_fullName.Split(CChar(" "))(_fullName.Split(CChar(" ")).Count - 1) m_course=_course End Sub #End Region Public PropertiesPublic Properties make up the specific "Exit Points" of the Object. They output the data in the private members, in a manner of your choosing.Here, I have given very basic examples for outputting the data, merely converting the local scope variables to public scope variables. For the name, I've added a simple concatenation to create a full name. Real world examples, of course, would be much more complex. #Region "Public Properties" Public ReadOnly Property SID As String Get Return m_sid End Get End Property Public ReadOnly Property Name As String Get Return String.Join(" ", m_firstName, m_lastName) End Get End Property Public ReadOnly Property Course As String Get Return m_course End Get End Property #End Region Public MethodsMethods are things that will affect and manipulate the data within the object. Public Methods are available outside the scope of the Object. Private Methods may be used to do internal manipulation of the data without allowing access from outside; this is mainly for utility or foundation level methods that alter the data in minor ways.In this basic example, I have overridden the canon .ToString() method to create a concatenated string of the relevant data. It uses all four of the input parameters. #Region "Public Methods" Public Overrides Function ToString() As String Return Me.Name + " (" + Me.SID + "), " + Me.Course End Function #End Region Full Class CodeHere is the code for the Student Class Object in full: Option Explicit On Option Strict On Namespace MMU Class Student #Region "Private Members" Private m_sid As String Private m_firstName As String Private m_lastName As String Private m_course As String #End Region #Region "Constructors" Sub New(ByVal _sid As String, ByVal _firstName As String, ByVal _lastName As String, ByVal _course As String) m_sid = _sid m_firstName = _firstName m_lastName = _lastName m_course = _course End Sub Sub New(ByVal _sid As String, ByVal _fullName As String, ByVal _course As String) m_sid = _sid m_firstName = _fullName.Split(CChar(" "))(0) m_lastName = _fullName.Split(CChar(" "))(_fullName.Split(CChar(" ")).Count - 1) m_course = _course End Sub #End Region #Region "Public Properties" Public ReadOnly Property SID As String Get Return m_sid End Get End Property Public ReadOnly Property Name As String Get Return String.Join(" ", m_firstName, m_lastName) End Get End Property Public ReadOnly Property Course As String Get Return m_course End Get End Property #End Region #Region "Public Methods" Public Overrides Function ToString() As String Return Me.Name + " (" + Me.SID + "), " + Me.Course End Function #End Region End Class End Namespace UsageThe usage for Objects is the same for using any other class. You must first declare the class, with any mandatory arguments and then you can use the methods and properties of that instance of the classIn this example, I have created two students, using both methods of construction and have used the .ToString() method on each of them to output the data. Both JohnDoe and JaneDoe are separate entities, or instances of the same class. What happens to one, will not affect the other. Sub Main() Dim JohnDoe As New MMU.Student("12345678", "John", "Doe", "BSc (Hons) Computer Network Technology") Dim JaneDoe As New MMU.Student("87654321", "Jane Doe", "BSc (Hons) Computer Network Technology") Console.WriteLine(JohnDoe.ToString()) Console.WriteLine(JaneDoe.ToString()) Console.ReadKey() End Sub Output John Doe (12345678), BSc (Hons) Computer Network Technology Jane Doe (87654321), BSc (Hons) Computer Network Technology Quote Link to comment Share on other sites More sharing options...
ApacheTech Consultancy Posted March 13, 2013 Share Posted March 13, 2013 The above is how to create the Class Objects ready to store, here is how to use the Strongly Typed Collections:AssumptionsI have made a few assumptions during this post: The reader understands VB.NET syntax Examples are given as a bare-bones demonstration only and any implementation will incorporate Defense Programming into it's design. Option Explicit in VB.NET is turned On Option Strict in VB.NET is turned On The reader understands that although this post is written using VB.NET syntax as an example language, the concept and implementation can be used in most modern high-level programming languages. The reader has already read my previous post: Object Orientated Programming (OOP) OverviewA strongly-typed collection is one where all the Types within a collection are known at compile and do not need to be cast during runtime, or outside of the collection itself.A Collection is similar to an Array, but much more powerful in the ways it can be used. Collections have a dynamic capacity, so if a new entity is added, the index will automatically increase. They are also sortable, enumerable and can be cast to many other forms of collection. Within this post, I will be using a simple List Collection, which is the most simple Collection to work with.Full CodeI have placed the full code for the project here and will expand on it below. I have expanded the Student Class Object slightly, adding in Set options within each property and removed the ReadOnly restriction.As mentioned in my previous post, this has merely expanded the use of the Student Class Object and has not altered any of it's uses prior to this post. Option Explicit On Option Strict On Module StudentData Sub Main() Dim ClassList As New MMU.StudentList ClassList.Add(New MMU.Student("12345678", "John", "Doe", "BSc (Hons) Computer Network Technology")) Dim JaneDoe As New MMU.Student("87654321", "Jane Doe", "BSc (Hons) Computer Network Technology") ClassList.Add(JaneDoe) Console.WriteLine(ClassList("12345678").ToString()) Console.WriteLine(ClassList(1).ToString()) Console.ReadKey() End Sub End Module Namespace MMU #Region "Student (Custom Class Object)" Class Student #Region "Private Members" Private m_sid As String Private m_firstName As String Private m_lastName As String Private m_course As String #End Region #Region "Constructors" Sub New(ByVal _sid As String, ByVal _firstName As String, ByVal _lastName As String, ByVal _course As String) m_sid = _sid m_firstName = _firstName m_lastName = _lastName m_course = _course End Sub Sub New(ByVal _sid As String, ByVal _fullName As String, ByVal _course As String) m_sid = _sid m_firstName = _fullName.Split(CChar(" "))(0) m_lastName = _fullName.Split(CChar(" "))(_fullName.Split(CChar(" ")).Count - 1) m_course = _course End Sub #End Region #Region "Public Properties" Public Property SID As String Get Return m_sid End Get Set(_sid As String) m_sid = _sid End Set End Property Public Property Name As String Get Return String.Join(" ", m_firstName, m_lastName) End Get Set(_fullName As String) m_firstName = _fullName.Split(CChar(" "))(0) m_lastName = _fullName.Split(CChar(" "))(_fullName.Split(CChar(" ")).Count - 1) End Set End Property Public Property Course As String Get Return m_course End Get Set(_course As String) m_course = _course End Set End Property #End Region #Region "Public Methods" Public Overrides Function ToString() As String Return Me.Name + " (" + Me.SID + "), " + Me.Course End Function #End Region End Class #End Region #Region "StudentList (Strongly Typed Collection)" Class StudentList #Region "Inheritance" Inherits List(Of MMU.Student) #End Region #Region "Default Overloaded Property" Default Overloads Property Item(ByVal _index As Integer) As MMU.Student Get Return MyBase.Item(_index) End Get Set(_student As MMU.Student) MyBase.Item(_index) = _student End Set End Property Default Overloads Property Item(ByVal _sid As String) As MMU.Student Get For Each Student As MMU.Student In Me If Student.SID = _sid Then Return MyBase.Item(Me.IndexOf(Student)) End If Next Throw New KeyNotFoundException("Student was not found in list.") Return Nothing End Get Set(_student As MMU.Student) For Each Student As MMU.Student In Me If Student.SID = _sid Then MyBase.Item(Me.IndexOf(Student)) = _student Else Throw New KeyNotFoundException("Student was not found in list.") End If Next End Set End Property #End Region End Class #End Region End Namespace Output John Doe (12345678), BSc (Hons) Computer Network Technology Jane Doe (87654321), BSc (Hons) Computer Network Technology InheritanceWhen a class inherits from another class, it becomes an extension of that class. The class from which we inherit is known as the Parent Class and any child gains the properties and methods of it's parent.Here, we are creating a Child Class, or Derived Class or the List(Of T) base Collection class. This means that everything that we could do with a list, we can now do with our own class.It is important to understand this difference as we continue on. The class we have created is now bound only to work with the type MMU.Student, and is now, therefore, strongly-typed. Class StudentList #Region "Inheritance" Inherits List(Of MMU.Student) #End Region End Class Default PropertiesBy specifying a Default Property, you are able to access that property directly by just specifying Object itself. Think of how you just specify Array(0).Property rather than Array.Item(0).Property, although both will work just as well.Here, we Overload the Item Property, just as we did previously with the constructor within the Student Object. This is so that, as well as the regular index iteration, we can also iterate through the List by the student numbers.It is important to specify within these default properties, only fields which are unique to each record. Like in a database, each entity in a collection is uniquely identified by it's index. Using non-unique fields has the possibility of bringing up multiple records.This is possible, by returning a new collection rather than an individual record, much like how multi-dimensional arrays work. However, this is beyond the scope of this demonstration. #Region "Default Overloaded Property" Default Overloads Property Item(ByVal _index As Integer) As MMU.Student Get Return MyBase.Item(_index) End Get Set(_student As MMU.Student) MyBase.Item(_index) = _student End Set End Property Default Overloads Property Item(ByVal _sid As String) As MMU.Student Get For Each Student As MMU.Student In Me If Student.SID = _sid Then Return MyBase.Item(Me.IndexOf(Student)) End If Next Throw New KeyNotFoundException("Student was not found in list.") Return Nothing End Get Set(_student As MMU.Student) For Each Student As MMU.Student In Me If Student.SID = _sid Then MyBase.Item(Me.IndexOf(Student)) = _student Else Throw New KeyNotFoundException("Student was not found in list.") End If Next End Set End Property #End Region UsageAs seen in the code above, we can enter the student's details in a number of different fashions as before and to output, you use the collection just like an array, but specifying the methods or properties you want to display from the Object held within the selected index.Final ThoughtIf you're still having problems with the idea of a strongly-typed collection, think of it like this: In a weakly-typed collection of Students, each index holds a Object of the Student Type. In a strongly-typed collection of Students, each index is a Student Object. Quote Link to comment Share on other sites More sharing options...
Scorpion Posted March 13, 2013 Author Share Posted March 13, 2013 This does look like what i want thank you, I will try this out once i get back to the program. Its long winded but that looks exactly what im after. I will post again once i've done/wrote it. Cant believe that i cant find a backup of my program that i had done this in, when i was only just a begineer at vb.net . Quote Link to comment Share on other sites More sharing options...
ApacheTech Consultancy Posted March 13, 2013 Share Posted March 13, 2013 (edited) Strongly Typed Collections are the base stone of any OOP-centric language. If you master them then you begin to think and plan your programs around STC principles. It's actually a very simple process once you've done it a few times. Edited March 13, 2013 by ApacheTech Consultancy Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.