SortedSet in Class does not expose correctly - vb.net

I have a weird problem that I can't seem to figure out. Even weirder is that I'm fairly sure it has worked in the past, but not anymore.
I have a class where I define a variable as SortedSet. In a function, I can reference the variable, but its SortedSet attributes are not exposed. If I use them anyway, some of them work, others don't. If I create that variable inside my function, all works as expected.
This is the code:
Public Class MyTest
Public MySortedSet = New SortedSet(Of String)()
Public Sub New()
Dim MySortedSet2 = New SortedSet(Of String)()
'Constructor. To use this, add Dim MyTest As MyTest to the Form1_load sub.
Me.MySortedSet.add("Test")
For Each Item In Me.MySortedSet
MsgBox(Item) 'This does print Test
Next Item
Me.MySortedSet.add '.add not exposed
MySortedSet2.add '.add is exposed
End Sub
End Class
See the screenshot below. The first example only has 4 items, where the 2nd example has a full list of parameters. I need to fix this using the first example, so the ElementAt one works. It works in the second example, but not in the first. It gives the error that ElementAt is not part of this object.
How can I get the full list of parameters for me.MySortedSet.??????

You should declare MySortedSet as a Property:
Public Class MyTest
Public Property MySortedSet As New SortedSet(Of String)()
Public Sub New()
Dim MySortedSet2 As New SortedSet(Of String)()
Me.MySortedSet.Add("Test")
For Each item As String In Me.MySortedSet
Debug.WriteLine(item)
Next item
Me.MySortedSet.Add("Test")
MySortedSet2.Add("Test")
End Sub
End Class
You should also indicate variable types every time you declare a variable, even in a For Each statement.

Related

Why does the Default Property access the setter when removing an item

In the code below, when trying to remove an item from the Cases list the code breaks in the Setter with an index out of bounds. When running the debugger in VisualStudio 2017 it successfully goes through the Remove() function and deletes the last item but after returning to Main() it will break on the Setter and the call stack says it is coming from the Remove call. Example code below:
Sub Main()
Dim Cases As Collection = New Collection()
Dim caseIndex As Integer = 2
Cases.Remove(Cases(caseIndex))
End Sub
Public Class Collection
Public WithEvents Cases As List(Of CaseClass)
Public Sub New()
Cases = New List(Of CaseClass)()
Cases.Add(New CaseClass)
Cases.Add(New CaseClass)
Cases.Add(New CaseClass)
End Sub
Default Public Property BeltCase(ByVal Index As Integer) As CaseClass
Get
Return Cases(Index)
End Get
Set(ByVal Value As CaseClass)
Cases(Index) = Value
End Set
End Property
Public Sub Remove(ByRef BeltCase As CaseClass)
Cases.Remove(BeltCase)
End Sub
End Class
Public Class CaseClass
Public test As Int16
End Class
Call Stack:
TestingVBBug.exe!TestingVBBug.Module1.Collection.set_BeltCase(Integer Index,TestingVBBug.Module1.CaseClass Value) Line 25 Basic
TestingVBBug.exe!TestingVBBug.Module1.Main() Line 6 Basic
So why would we be going through the Setter at all. And why does that happen after we exit the remove function?
The problem is caused by your Remove() method, that is, you have a ByRef parameter (for some reason). When you use ByRef, any changes made to the parameter inside the method must be reflected to the variable that was passed to the method. That happens by reassigning the value to the original variable.
In your case, it works like this:
The Remove() method is called and a variable (Cases(caseIndex)) is passed to it.
Some work is done inside the Remove() method which might, or might not include changing the value of the parameter BeltCase.
The value of the parameter BeltCase gets reassigned to the variable that was originally passed to the method (which is Cases(caseIndex)).
As a result of the above step, the setter of the BeltCase property gets called with Index = 2 which raises the out of range exception because Cases(2) doesn't exist (was removed).
To confirm, you can see this problem go away when you replace this line:
Cases.Remove(Cases(caseIndex))
..with:
Dim myCase As CaseClass = Cases(caseIndex)
Cases.Remove(myCase)
That way, you create a new variable which refers to the same CaseClass object and most importantly avoid calling the setter of your Collection.BeltClase property.
However, a better solution would be to not use ByRef in the first place since you don't seem to need it in this situation. So, simply use Public Sub Remove(ByVal BeltCase As CaseClass) instead.
Check this question for more about ByVal and ByRef with objects.
One last thing, please don't call your class Collection because it can be very confusing to anyone looking at your project.

Building an ArrayList in an external class - vb.net

I have an ArrayList defined in Class A. Then I want to build this array in Class B and use it in Class A.
I defined the ArrayList as:
Public arrayList As ArrayList
Then, in Class B I do:
Dim trLogkEmpty As New A
'Loop with strEspece definition
trLogkEmpty.arrayList.Add(strEspece)
'End Loop
The program throws me this error:
NullReferenceException
I don't know why, because strEspece has never become null (I tested it). I don't know if there is another reason.
Also, when I loop through the arrayList elements in Class A, I get again NullReferenceException. This is the loop code:
For Each logkNull In Me.arrayElemWithLogkEmpty
Console.WriteLine(logkNull)
Next
I don't know what happens with the first exception, but the code runs "correctly". In the second exception I guess that is something like I'm loosing the elements values of the array. I don't know how to solve it...any help? I accept different ways to solve it!
You are making two of the same mistake. A NullReferenceException means that you are attempting to access a property or method on an object that hasn't been instantiated yet. You are attempting to access both A and A.arrayList without first creating new instances of them.
So, instead of just:
trLogkEmpty.arrayList.Add(strEspece)
You should have:
Dim trLogkEmpty As New A()
trLogkEmpty.arrayList = New ArrayList()
trLogkEmpty.arrayList.Add(strEspece)
However, I must insist that you avoid ArrayList, and also that you avoid instantiating a public member of a class from outside that class. I would suggest using a strongly-typed collection class such as List(Of T), and having a read-only property in A's take care of its instantiation and visibility so the collection (not its contents) can't be modified outside of A:
Public Class A
Private _myList As IList(Of String)
Public ReadOnly Property MyList As IList(Of String)
Get
If _myList Is Nothing Then
_myList = New List(Of String)
End If
Return _myList
End Get
End Property
End Class
And now you have:
Dim trLogkEmpty As New A()
trLogkEmpty.MyList.Add(strEspece)
You're probably going to need to keep your instance of A around, so class B should probably look somewhat like:
Public Class B
Private _a As A
Public Sub New()
_a = New A()
End Sub
' ... your methods that use _a.MyList
End Class
I got it finally. When I initialised the array in class 'A' I forget to create an instance of ArrayList class, specifically, I forget to put New:
Public arrayElemWithLogkEmpty As New ArrayList
So, partly, #Blackwood was right!
Thank you all and forgive me for my basic knowledge about vb.net.

So a VB interface can't have shared functions. Is there an alternative to creating dummy objects?

To avoid getting into the weeds on my particular program, let me just create a simplified case.
I have a generic class that should work on a variety of objects. Each of those objects must implement a certain interface.
What I WANT to say is something like:
Public Interface GenThing
Shared Function thing_name() As String ' This doesn't work! Can't be shared!
Sub FillOne(row As DataRow)
End Interface
public class Thing1
implements GenThing
public shared function thing_name() as string implements GenThing.thing_name
return "thing number one"
end function
public sub FillOne(row as DataRow) implements GenThing.MakeOne
... bunch of work ...
end sub
end class
public class ThingUtil(of T as {GenThing,New})
public function GetList(id as integer) as List(of T)
dim name=T.thing_name() ' This doesn't work!
dim ds as DataSet=GetData(name,id) ' bunch of work here that's the whole point of the class but not relevant to the question
dim my_list = new List(of T)
for each row as DataRow in ds.tables(0).rows
dim my_t = new T()
my_t.FillOne(row)
my_list.add(my_t)
next
return my_list
end function
end class
Do you get my problem? I need every class that implements the interface to have a function that returns a "name" that is used to get the data that is needed to create an instance of the object. But I need to know this name BEFORE I create the instance, because I need it to be able to create the instance. But VB doesn't allow an interface to have a shared function, so what I want to write doesn't work.
So what I've done is this:
I make thing_name not shared.
Then instead of simply "dim name=T.thing_name()", I write
dim dummy = new T()
dim name = dummy.thing_name()
Okay, it works, but it seems really ugly. I create an instance of the object, with all the overhead that that involves, just to get a piece of constant text.
Is there a better way? Or am I making a big deal out of nothing?
Update
I see that two people voted to close this question on the grounds that it is the same as "Why can't we have shared functions in an interface?"
I am not asking why I can't have a shared. I am saying, GIVEN that I can't, how do I solve this particular problem?
There's no really simple way of fixing this, no.
Depending on what thing_name does, however, you might approach things in a different way. If each implementation just returns a constant value, then it's effectively metadata about the class - and could be described in an attribute instead, which can be fetched at execution time. (See Type.GetCustomAttributes.) Unfortunately you can't then enforce all types implementing the interface to be decorated with the attribute - but you could write a unit test to check this pretty easily.
If thing_name needs to really do work at execution time, that's tougher. You could potentially look for a well-known shared method name instead and execute that via reflection (and again have unit tests to check that it's implemented properly).
I realize this is from a few years ago, but running into a similar problem, I wanted to offer a different solution. Pass a delegate as parameter to the ThingUtil constructor. You avoid having to put a shared method in an interface, and the constructor will force you to include the parameter at compile time.
You can add more delegates if needed, or to make it even simpler in this case, just pass name as a string instead of get_name as a delegate.
Define the delegate in the interface:
Public Interface GenThing
Delegate Function ThingNameDelegate() As String
Sub FillOne(row As DataRow)
End Interface
Public Class Thing1
Implements GenThing
Public Shared Function thing_name() As String 'name this whatever you want
Return "thing number one"
End Function
Public Sub FillOne(row As DataRow) Implements GenThing.FillOne
'do stuff
End Sub
End Class
In ThingUtil, add a member to store the delegate, a constructor parameter to to accept, and call it with .Invoke():
Public Class ThingUtil(Of T As {GenThing, New})
Private m_thing_name As GenThing.ThingNameDelegate
Public Sub New(thing_name As GenThing.ThingNameDelegate)
m_thing_name = thing_name
End Sub
Public Function GetList(id As Integer) As List(Of T)
Dim name = m_thing_name.Invoke()
Dim ds As DataSet = GetData(name, id) ' bunch of work here that's the whole point of the class but not relevant to the question
Dim my_list = New List(Of T)
For Each row As DataRow In ds.Tables(0).Rows
Dim my_t = New T()
my_t.FillOne(row)
my_list.Add(my_t)
Next
Return my_list
End Function
End Class
Finally, use it like this:
Dim tu as new ThingUtil(Of Thing1)(AddressOf Thing1.get_name)
tu.GetList(1)

How to instantiate Class object with varying number of property values

Been working a lot with custom classes lately and I love the power you can have with them but I have come across something that I'm not able to solve and/or find anything helpful online.
I have a list of a class with properties I'm looking to only store information pulled from a database into.
Public Class CustomClass
Public _Values As String
Public _Variables As String
Public ReadOnly Property Values() As String
Get
Return _Values
End Get
End Property
Public ReadOnly Property Variables() As String
Get
Return _Variables
End Get
End Property
Sub New(ByVal values As String, ByVal variables As String)
_Values = values
_Variables = variables
End Sub
End Class
I will be iterating through some database entries, and I'm looking to store them into the appropriate property when I hit them (since I won't have them all available immediately, which is part of my problem). I want to just be able to add either the value or the variable at a time and not both of them, but since I have the sub procedure 'New' passing two arguments, it will always require passing them both. I've found the only way around this is by making them optional fields which I don't feel is the right way to solve this. Is what I'm looking to do possible with a class or would it be simpler by using a structure?
You can overload the constructor:
Friend Class Foo
' using auto-implement props:
Public Property Name As String ' creates a _Name backing field
Public Property Value as Integer
Public Sub New(newN as String, newV as Integer)
' access "hidden" backing fields if you want:
_Name = newN
_Value = newV
End Sub
Public Sub New() ' simple ctor
End Sub
Public Sub New(justName As String)
' via the prop
Name = justName
End Sub
End Class
You now have 3 ways to create the object: with full initialization, partial (name only) or as a blank object. You will often need a "simple constructor" - one with no params - for other purposes: serializers, Collection editors and the like will have no idea how to use the parameterized constructors and will require a simple one.
If rules in the App were that there was no reason for a MyFoo to ever exist unless both Name and Value being defined, implementing only the New(String, Integer) ctor enforces that rule. That is, it is first about the app rules, then about coding convenience.
Dim myFoo As New Foo ' empty one
myFoo.Name = "ziggy" ' we only know part of it
Since the default of string is nothing, you could pass nothing for the value you don't have. IE
Collection.Add(New CustomClass("My Value",Nothing))
Every type has a default, so this works with more than just strings.

VB.NET Add row data to public class / public field of type List(Of T) Object reference not set to an instance of an object

I am trying to add rows to a public class that has public fields and am getting an error: Object reference not set to an instance of an object
Public Class EmailRecipient
EmailAddress As String = ""
FullName As String = ""
End Class
Public Class EmailDetails
Public FromEmail As String = ""
Public ToEmails As List(Of Emails) = nothing
End Class
Public Sub SetEmailDetails
'Populate EmailRecipient Class
Dim er As New EmailRecipient
er.EmailAddress = "rodney#norespect.com"
er.FullName = "Rodney Dangerfield"
'Populate EmailDetails Class
Dim ed As New EmailDetails
ed.FromEmail = "sender#danger.com" 'This works fine
ed.ToEmails.Add(er) 'Here error happens
End Sub
I'm guessing I need to create an instance of the EmailRecipient class before I can add an item to it.
Not sure how to do that with a Public Field in a Public Class??
It's been a rough day. I got up this morning, put a shirt on and a button fell off. I picked up my briefcase and the handle came off. I'm afraid to go to the bathroom.
Thanks for the help :-)
I'm guessing I need to create an instance of the EmailRecipient class
You already have an instance of the EmailRecipient class. That's your er variable. You actually have two errors here. First, you explicitly set ToEmails to Nothing:
Public ToEmails As List(Of Emails) = nothing
This means that your ToEmails variable is a Null Reference. It doesn't have an actual object yet.
The second issue is that you shouldn't get that excpetion, because this shouldn't even compile. You define ToEmails as a List(Of Emails), but tried to add an object of type "EmailRecepient" to it. That should be a compiler error. If it's not, you need to turn Option Strict or Option Infer back on.
So what you really need is an instance of a the List(Of EmailRecipient) type. Fix the bad line of code like this:
Public ToEmails As New List(Of EmailRecipient)