What does variable-initialization line do in VB.Net? - vb.net

Can someone please tell what the following line of VB.Net is initializing:
Dim x As SomeType() = New SomeType(0) {}
What holds x variable? Is it an array? How can it be translated to C# for example?
I guess SomeType is probably an anonymous type, but still have no clue...

The line:
Dim x As SomeType() = New SomeType(0) {}
declares an array of SomeType objects, which can hold one instance of SomeType.
When declaring an array of objects the value that is passed into the constructor is the max index of the array. So this declaration is basically declaring an array with a length of 1. The {} portion of the line is where you could define the values that should be stored in the array. If you were to change SomeType to integer you could instantiate and fill your array like:
Dim intArray as Integer() = New Integer(0) {7}
and that would give the first instance stored in the intArray variable a value of 7.
SomeType is not an anonymous type. SomeType would be a class that would have to be defined somewhere in your app.
In C# I think the sytax would look like:
SomeType[] x = new SomeType[0];
I'm not exactly sure how you would accomplish the {} portion of the VB.NET line in C#.

It's simply declaring and initializing an array of a given type. In C# I think it would be, quite similarly:
SomeType[] x = new SomeType[0] { };
Is it an array?
Yes. VB uses () for arrays instead of C#'s [].
I guess SomeType is probably an anonymous type
No, it's a defined static type like any other.

Related

Why does this syntax where we declare an array and converting it to list work?

I saw someone write this
Dim trueifnotprime = New Boolean(99) {}.ToList
And it works. I do not understand why.
What is actually going on? What is New Boolean(99)? Am I creating a boolean array or am I calling boolean constructor with 99 parameter? Then what is the {} thingy? What kind of notation is this?
The New refers to the constructor of the array.
Boolean is the Data Type
(99) is the size of the array. 99 being the index of the upper bound of the array.
{} could contain the values for the elements of the array. Since it is empty the array is initialized with the default value for Boolean, False.
.ToList converts the array to a List(Of T)

How do I pass parameter of inline new object?

I have a method that accepts a string as a parameter.
The string I need to pass is the property of an instantiated object.
I don't need the object to stick around once I get the value of that property.
I know I can do this like so:
Dim x As New myClass1
foo.thing1 = MyMethod(x.Name)
x = New MyClass2
foo.thing2 = MyMethod(x.Name)
'etc...
But I would prefer to do this inline if possible, since I have to do this several times in a row with different MyClass types.
EDIT:
Figured it out:
foo.thing = MyMethod(new MyClass().Name)
Try
foo.thing1 = MyMethod((New myClass1).Name)
foo.thing2 = MyMethod((New MyClass2).Name)
You need the braces around New myClass1, otherwise VB thinks you are trying to create an object of type myClass1.Name, which, of course, does not exist.
foo.thing = MyMethod(new MyClass().Name)

Create Data.SqlClient.SqlParameter with a SqlDataType, Size AND Value inline?

I have a function which can take a number of SqlParameter objects:
Public Shared Function RunSQL(sqlInput As String, Optional params As Data.SqlClient.SqlParameter() = Nothing) As String
The aim is basically being able to call the function and create the parameters if needed, as needed.
Unfortunately, there do not appear to be any constructors available that will allow me to specify the Value as well as the SqlDbType without having to add lots of additional parameters (that I do not need) as well.
The desired outcome would be something like:
Dim myStr As String = RunSQL("spMyStoredProc", {New Data.SqlClient.SqlParameter("#FieldName", Data.SqlDbType.NVarChar, 50, "MyValue")})
Obviously as the constructor for this does not exist, my question is basically to ask whether or not there is any way around this, as in any alternative, etc whilst still allowing the convenience of declaring the parameters in the function call?
I'd rather not have to declare all of my parameters beforehand just to set the Value property.
First, your code compiles but the last parameter is not the value but the source-column-name.
But you could use the With statement to assign the Value:
Dim myStr As String = RunSQL("spMyStoredProc",
{
New Data.SqlClient.SqlParameter("#FieldName", Data.SqlDbType.NVarChar, 50) With {.Value = "MyValue"}
})
See: Object Initializers

How to create a Dictionary with for value type that is known?

I want to create a Dictionary where the Key type is Integer and the Value type is the type of the class I am currently executing in.
I've tried the following:
Dim col as new Dictionary(Of Integer, Me.GetType())
but I am getting an error stating that `keyword does not name a type.
How do I create a dictionary based on the type of the executing class?
C# sample of creating dictionary of int to a type.
Methods used:
Type.MakeGenericType
Type.GetConstructor
ConstructorInfo.Invoke
The problem is mainly to express resulting type in somewhat type-safe manner. In Dictionary case one may resort to IDictionary, or continue to use reflection to manipulate objects.
It may also be possible to somehow express most manipulation with generic code which is invoked by more reflection with MakeGenericMethod
Sample:
var myType = typeof(Guid); // some type
// get type of future dictionary
Type generic = typeof(Dictionary<,>);
Type[] typeArgs = { typeof(int), myType };
var concrete = generic.MakeGenericType(typeArgs);
// get and call constructor
var constructor = concrete.GetConstructor(new Type[0]);
var dictionary = (IDictionary)constructor.Invoke(new object[0]);
// use non-generic version of interface to add items
dictionary.Add(5, new Guid());
Console.Write(dictionary[5]);
// trying to add item of wrong type will obviously fail
// dictionary.Add(6, "test");
Just use the class name Dim col as new Dictionary(Of Integer, MyClass)
On a side not using integer as your key can get confusing since a dictionary also uses integer for the index. If the keys are to be consecutive integers, you might be better served by a list.

beginner question, calling a function/assign property etc... of an object inside an array

So if I create an object test, and it has a property color. When I add this object to an array list I typically can access this using myarray(0).color but intellisense doesn't 'know' that I have a 'test' object inside the array. It would let me type myarray(0).whatever but would then crash if I made typo. It seems like I should be able to let it know what type of object I am trying to work with inside the arraylist.
In code maybe something like this
dim testobject as new test
testobject.color = "red"
dim testarray as new arraylist
testarray.add(testobject)
testarray(0).color = "blue"
Could someone tell me the name of this concept, and a more correct(if there is one) of how I should be doing this?
Thanks for any thoughts!
use generics instead
dim a as System.collections.generic.List(of test)
a(0).asf ' Errror