What is the preferred syntax for declaring an array in VB.NET? - arrays

Between the following options, which is the preferred syntax for declaring arrays in VB.NET?
Dim numbers1() As Integer
vs.
Dim numbers2 As Integer()
The MSDN article How to: Initialize an Array Variable in Visual Basic mentions the second option as the preferred syntax: Dim chars2 As Char()..., but the first option seems more common in other documentation. The second option might be confusing since it's so similar to calling a constructor with no arguments.
E.g.
Dim customer As New Customer() ' Initialize a new Customer
which looks similar to:
Dim customer As Customer() ' An uninitialized array of Customers
This question is similar to but different from: Different ways of declaring arrays in VB.NET.

I'll chime in here.
I've seen more of style 1 in code than style two, however there are some minor odd inconsistencies with syntax when it comes to properties.
My theory is the reason the parentheses after is preferred is to make it more consistent with declaring a property that is an array
Public Property x As Integer() 'is an array
Public Property y() As Integer 'is NOT an array
That being said...use Lists :)

Related

Remove an item at a specific Index from a dynamic String Array

I have a dynamic string array and I have populated it with some dynamic values using ReDim etc. I would like to delete an item from the string array at a specific position. I have read about using a Where condition using System.Linq but can't really get a proper answer to this. Any suggestions?
Dim dynamic() as String
...
Redim dynamic(2)
..
dynamic(0) = Apple
dynamic(1) = Banana
dynamic(2) = Orange
..
dynamic(i).Remove... etc?
As others have mentioned, there is technically no way to remove an element from an array. The only way to modify the number of elements in the array is to create a whole new array and copy the contents from the one to the other. There are more convenient methods you can use to do it, but in the end, that's what they are actually doing for you, just behind the scenes.
If you are going to be doing a lot of that kind of thing, I would recommend using the List(Of String) class rather than a String array. As others have pointed out, the List(Of T) class is specifically designed to make those kinds of dynamic functions more simple. If, you ever need the list as an array, you can very easily (and efficiently) convert it to an array like this:
Dim myList As New List(Of String)()
myList.Add("Apple")
myList.Add("Banana")
myList.Add("Orange")
myList.RemoveAt(1)
Dim myArray() As String = myList.ToArray()
However, if you really must have it as an array, LINQ does make it a bit easier. By importing the LINQ namespace, many new LINQ extension methods will be added to arrays (and any other list or enumerable objects). For instance, you could use LINQ's Except method, like this:
Dim dynamic() As String = {"Apple", "Banana", "Orange"}
dynamic = dynamic.Except({"Banana"}).ToArray()
Notice that the Except method returns an enumerable object, but not an array. To convert it to an array, you'll need to additionally call LINQ's ToArray method, as in the above example. That above example removes the string "Banana" from the middle of the array. If, however, you don't know the value and you just want to remove it by index, LINQ doesn't provide a way to filter by index like that. You could still use the Except method like this, though:
Dim dynamic() As String = {"Apple", "Banana", "Orange"}
dynamic = dynamic.Except({dynamic(1)}).ToArray()
You may be wondering why I put the curly brackets around the parameter passed to the Except method. I did that because the Except method actually takes a list of parameters (IEnumerable, to be specific). Since array's implement IEnumerable (as well as IList, by the way), I just wrapped the parameter in an array before passing it to the method. The interesting upshot of this is that if you have multiple items to remove, you could do them all in one command, like this:
Dim dynamic() As String = {"Apple", "Banana", "Orange"}
dynamic = dynamic.Except({"Apple", "Banana"}).ToArray()
You can't do it directly with arrays. But you can do this:
Dim tmp = New List(Of string)(dynamic)
tmp.RemoveAt(index)
dynamic = tmp.ToArray()

Array variable is used before assigned a value

When I rebuild the solution I get the warning:
"Variable 'aMyArray' is used before it has been assigned a value."
A function in VB.NET uses an array which is dynamically populated.
Example:
Function MyArray()
Try
Dim aMyArray()
For i = 0 to 100
ReDim Preserve aMyArray(i)
Next
Catch ex As Exception
End Try
End Function
How should I declare a dynamically populated array to eliminate this warning?
I like to use the CreateInstance to avoid possible errors:
Dim aMyArray() as string = Array.CreateInstance(GetType(String),0)
A. Your function returns nothing, so you should also have a warning about that
B. You seriously need to turn on Option Strict and let the compiler point out other errors like aMyArray has no Type.
C. Never use and empty Try/Catch; if there is an exception, you want to know when something goes wrong (and where) so you can fix it.
D. Avoid arrays like the plague. ReDim Preserve aMyArray(i) creates a new array and then copies all the data to the new structure. This can be costly in terms of performance if it is a large array of something like strings. Net has several very nice collections such as List(of T) which do not need to be explicitly resized:
Private myList As New List(of String) ' or Integer, Decimal or even MyClassObject
...
myList.Add("Hello")
myList.Add("Lists...")
myList.Add("Goodbye")
myList.Add("Arrays")
D(1). The result of using a List would mean that entire procedure can be done away with. Just add new things to the list as needed.
E. The code posted cant actually result in the warning because you dont ever add a value to it. Adding: aMyArray(2) = 2 after the loop will result in the warning. This is because you have never fully declared the array (size and type) as in:
Dim aMyArray(100) As String
ReDim simply resizes the array which isnt the same thing.
F. Since there is nothing in your new array, there is no reason to use ReDim Preserve because there is nothing to preserve. I'll assume that is supposed to be some calculation. On the other hand, if you are trying to resize an existing array, it should be a Sub.
We are all left to guess if it really is meant to modify an existing array (based on ReDim Preserve) or return a new array of stuff (considering the array is declared in the procedure).
Again, none of this is needed using a List, Dictionary or other Collection Type.

store singledimensional and multidimensional in same key:value container instead of Structure?

I'm wrapping up my ajax copy & paste with explicit error reporting.
The final Function Returns three Keys with three Lists as Values.
psuedo
Return New Dictionary(Of String, List(Of Object)) From {
{"duplicatePoints", UniqueErrorsReport},
{"inexistentPoints", ExistenceErrorsReport},
{"insertedRows", InsertedRows}
}
Two are List(Of Object)s and one is a List(Of Array). I hate doing the same thing twice, so I'd prefer not to use a Structure.
I acted all smart and thought by declaring a List(Of Array) rather than a List( Of Object()) would let me slide since Array descends from Object (if I'm reading it correctly). Nope, at least not the way I'm doing it:
Unable to cast object of type 'System.Collections.Generic.List`1[System.Array]'
to type 'System.Collections.Generic.List`1[System.Object]'
Is it possible to avoid using a Structure and simply Return containers of both non-multidimensionals and multidimensionals as Values in the same Key: Value container?
Is it possible to avoid using a Structure and simply Return containers of both non-multidimensionals and multidimensionals as Values in the same Key: Value container?
No, this is not possible. You have to convert your array to a list or your lists to array.
This is like if you try to store integers and strings in the same List(Of String).
You can not have different datatypes in the same Generic.List.
Unless you have dynamic results I would try to avoid using a dictionary here, and rather use a custom, class (like below):
Public Class ErrorReport
Public DuplicatePoints as List(Of UniqueErrorsReport)
Public InexistentPoints as List(Of ExistenceErrorsReport)
Public InsertedRow as List(Of InsertedRow)
End Class
I would highly recommend against List(Of Object), because they cost you performance (boxing and unboxing) and the more important reason: it is prone to errors because you can not detect errors in compile time.

EquivalentC# coding for Dim dataTable As DataTable = CType(sender, GridView).DataSource

i am trying to convert Vb.net To C#.net. could any one please help me to find the Equivalent C# coding for Dim dataTable As DataTable = CType(sender, GridView).DataSource.
and also,any tip for soring datas in data gridview.
thanks
You mean like this?:
DataTable dataTable = ((GridView)sender).DataSource;
To cast types in C#, you put the type in parentheses before the value:
(GridView)sender
Then, to access properties on it, you'll want to wrap the whole thing in parentheses:
((GridView)sender).DataSource
(This is because otherwise you'd be trying to call .DataSource on the un-cast sender which would fail.)
Then to declare a value (the variable that you're assigning), the standard syntax is to specify the type and then the variable name:
DataTable dataTable
(I highly recommend using a better variable name, by the way. C# is case-sensitive, so this is valid. But it's unintuitive at best.)
In C# you can also use the var keyword to infer the type, often resulting in cleaner code:
var dataTable = new DataTable();
This only works if there's an inferrable type from the right side of the assignment. Since the DataSource property isn't specifically of type DataTable then you don't want to use var in this particular case, since it would result in an Object (which isn't what you're looking for). But it can be used in cases like my last example above this paragraph where you don't want to repeat the type name twice in the same line of code.
DataTable dataTable = ((GridView)sender).DataSource
Regarding sorting in a GridView, see Sorting Data in a GridView Web Server Control, then post a question with what you have tried if you're having problems.

ReDim an Array Pointer VB6

I'm trying to ReDim a member object array from a different class. For example:
Class1.cls
Dim mStuffArray() As New clsStuff
Property Get StuffArray() As clsStuff()
StuffArray = mStuffArray
End Property
Class2.cls
Private Sub Foo(ByRef pClass1 As Class1)
Dim tStuffArray() As clsStuff
tStuffArray = pClass1.StuffArray
ReDim tStuffArray(1 To 2)
End Private
The problem here is that Foo doesn't seem to be ReDim'ing the member mStuffArray in Class1. Any idea what I'm doing wrong? Forgive me if my VB6 looks odd or the naming conventions aren't standard, I had to dive into some old legacy code and am new to VB6
Dave
Redim doesn't make a copy of the array.
I think it's more likely that 4eturning the array from a property get creates a copy. The docs aren't very clear. http://msdn.microsoft.com/en-us/library/aa261343(VS.60).aspx
It would be simpler to use a Public member variable. And why not use a Collection rather than an array?
I've never looked into VB6, but if I were to take a guess, I think when you use ReDim, it creates a copy of the existing Array and changes tStuffArray to point to the new copy. However, pClass1.mStuffArray still references the old array.
The documentation for ReDim states that "ReDim creates a new array, copying all the elements from the existing array"
I would recommend adding a method to to Class1 that performs ReDim on the private mStuffArray variable.
Dim mStuffArray() As New clsStuff
Property Get StuffArray() As clsStuff()
StuffArray = mStuffArray
End Property
Sub Foo()
ReDim mStuffArray(1 To 2)
End Sub
Hopefully this works. As I said, I'm not a VB6 programmer, so I may be off on this.
You might also want to consider the Dictionary object.

Resources