I'm trying to write a class in C# that supports the Item operators in VB6 (obj("Name") and obj!Name) through COM. I'm using a public class with a corresponding interface.
I have successfully overloaded the square bracket operators in C# and I can call the getter function with the proper operators from VB6, but I'm having trouble with calling the setter function. The error I usually get is "Object doesn't support this property or method".
Here's where it get's tricky:
When I don't define the interface and use the default COM object that is generated from my class, I can successfully use both the getter and setter functions, along with all of my other public functions in the class. However, there is a serious performance degradation in the getter function (about 5x) when I do this, and that is something that I can't live with for this project.
I've looked into early/late binding, and I'm guessing this has something to do with it, but I don't know enough to figure out what is actually going on.
Can anyone explain this for me?
Here's my C# class and interface:
public interface IExampleClass
{
bool Property1 { get; }
void Update();
void SetValue(string name, dynamic value)
dynamic this[string name] { get; set; }
}
[ClassInterface(ClassInterfaceType.None)]
public class ExampleClass : IExampleClass
{
private CustomObject obj;
public ExampleClass()
{
this.obj = new CustomObject(); // This has data when initialized
}
public bool Property1 => obj.Property1;
public void Update() => obj.Update();
public void SetValue(string name, dynamic value) => obj.SetValue(name, value);
public dynamic this[string name]
{
get
{
dynamic item = obj.GetValue(name);
// do something with item
return item;
}
set { obj.SetValue(name, value); }
}
}
And my VB6 test script:
Sub TestItemProperty()
Dim obj As ExampleClass
Set obj = New ExampleClass
'Test getter function
MsgBox obj!Name 'This works
MsgBox obj("Name") 'This works
'Test setting
obj.SetValue "Name", "John" 'This works
'Test setter function
obj!Name = "John" 'This doesn't work
obj("Name") = "John" 'This doesn't work
End Sub