I have written a C# library(Kvp) for VBA which is essentially a wrapper for a C# dictionary. All of the methods I have implemented work fine from VBA. However the indexer is throwing errors when I assign to an item in the Dictionary (the same problem occurs if I change from a dictionary to a HashTable).
In VBA
myObject.Item(Index) = a_value
throws an error saying that an object is required.
If I cast myObject
to Object then the indexer works as expected.
Dim myObj as Object
Set myObj = myObject
myObj.Item(Index) = a_value
To confirm that the Indexer was the problem I added GetItem
and SetItem
methods to the C# library and found that these worked as expected.
In the Interface
dynamic this[dynamic Key] { get; set; }
dynamic GetItem(dynamic myIndex);
void SetItem(dynamic myIndex, dynamic myValue);
In the Implementation
private Dictionary<dynamic, dynamic> MyKvp = new Dictionary<dynamic, dynamic>();
public dynamic this[dynamic Key]
{
get
{
return MyKvp[Key];
}
set
{
MyKvp[Key] = value;
}
public dynamic GetItem(dynamic myIndex)
{
return MyKvp[myIndex];
}
}
public void SetItem(dynamic myIndex, dynamic myValue)
{
MyKvp[myIndex] = myValue;
}
I can continue with the cast to Object workaround but to be honest it is a bit of a pain as it means that everywhere I change from Scripting.Dictionary to myObject I have to update the associated code. Of course I could revert to implementing myObject in VBA but I'm trying to learn c# and this library is my first project in the learning curve. Please note that I am not a professional programmer.
An of course the question is. How do I revise the C# library such that the Indexer works as expected in VBA?
Amended 13 Dec
Please note that I have a long list of unit tests using the Rubberduck add in. All tests pass except the Indexer assignment. The Indexer assignment test works if I VBA cast to an object as explained above.
Amedenment 2 13 Dec Updated as Amendment 4
In respone to @Gser'g question I've corrected the image for the Kvp Object and also added an image of the IKvp interface .
In the Interface
[Guid("6DC1808F-81BA-4DE0-9F7C-42EA11621B7E")]
[ComVisible(true)]
[InterfaceType(ComInterfaceType.InterfaceIsDual)]
public interface IKvp
In the Implementation
[Guid("434C844C-9FA2-4EC6-AB75-45D3013D75BE")]
[ComVisible(true)]
[ClassInterface(ClassInterfaceType.AutoDual)]
public class Kvp : IKvp, IEnumerable
Amendment 3 A confession
I have asked the same question in Code Review but its not getting much interest. The whole code for the Kvp object is included at
https://codereview.stackexchange.com/questions/233671/c-dictionary-wrapper-for-vba