How to create a Dictionary with for value type that is known? - vb.net

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.

Related

Can't use observableArrayList as value of hashmap in kotlin

I am trying to create a hashmap of a generic type to an array list type from FX Collections.
private val items = FXCollections.observableArrayList<T>()
private val itemsData = hashMapOf<T, FXCollections.observableArrayList<ItemData<T>>>()
The first line works fine, the second gives me a red line under 'observableArrayList'.
Unresolved reference: observableArrayList
This also works fine:
private val itemsData = hashMapOf<T, ItemData<T>>()
I'm new to kotlin and javafx, but even if importing observableArrayList directly doesn't help..
You're confusing a type with an object.
FXCollections.observableArrayList is a method that returns an instance of type ObservableList<E>. The declaration of the HashMap needs a type in the generics though.
Give this a try:
val itemsData = hashMapOf<T, ObservableList<ItemData<T>>>();
A simpler example as an explaination:
// delcare that my password storage has a string type as key and a string type as value
val myPasswords = hashMapOf<String, String>();
// add a pair of string instances
myPasswords["stackoverflow.com"] = "topsecret"

in kotlin how to put function reference in an array

Having class member function like:
private fun getData1(uuid:String): IData? {
...
}
private fun getData2(uuid:String): IData? {
...
}
private fun getData3(uuid:String): IData? {
...
}
and would like to put in a function reference array:
var funArray = ArrayList<(uuid: String) -> IData?> (
this::getData1,
this::getData2,
this::getData3)
it does not compile:
None of the following functions can be called with the arguments
supplied:
public final fun <E> <init>(): kotlin.collections.ArrayList<(uuid: String) -> IData?> /* = java.util.ArrayList<(uuid: String) -> IData?> */ defined in kotlin.collections.ArrayList ...
if do:
var funArray: ArrayList<(uuid: String) -> IData?> = ArrayList<(uuid: String) -> IData?>(3)
funArray[0] = this::getData1 //<== crash at here
funArray[1] = this::getData2
funArray[2] = this::getData3
crash with exception
java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
How to put function reference in an array?
The first attempt fails because ArrayList doesn't have a constructor taking (a variable argument list of) values.
You can get pretty much the same effect by replacing ArrayList with listOf() (or, if you need mutability, mutableListOf()), as that does take a vararg list:
var functions = listOf<(uuid: String) -> IData?>(
this::getData1,
this::getData2,
this::getData3)
That's perhaps the most natural solution.  (However, mutableListOf() is only guaranteed to return a MutableList implementation; it may not be an ArrayList.)
The second attempt fails because it's constructing an empty list.
(The ArrayList constructor it uses takes a parameter called initialCapacity; it ensures that the list could take at least 3 elements without needing to reallocate its arrays, but its initial size is zero.)
Perhaps the confusion is because although you say you ‘would like to put in a function reference array’, you're creating a List, not an Array.
(The ArrayList class is an implementation of the List interface which happens to use an array internally.  This follows the Java convention of naming implementation classes as <Implementation><Interface>.)
If you need to create an actual array, you could use arrayOf() in the first example:
var functions = arrayOf<(uuid: String) -> IData?>(
this::getData1,
this::getData2,
this::getData3)
Lists are probably used more widely than arrays in Kotlin, as they're more flexible.  (You can choose between many different implementations, with different characteristics.  They work better with generics; for example, you can create a List of a generic type.  You can make them immutable.  And of course if they're mutable, they can grow and shrink.)
But arrays have their place too, especially if performance is important, you need to interoperate with code that uses an array, and/or the size is fixed.

What does variable-initialization line do in 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.

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