Sunday, 21 July 2019

VBA - Anonymous objects

So in Java, C# and other object orientated languages one has the capability to create an object without assigning to a variable, call a method on it and then throw it away in a tight little block of code. The line of code would look something like this...

{  
   print((new Class1).Greeting);
}

This is called an anonymous object. If you tried this in VBA you would get a syntax error

Sub SyntaxError()
    '* the following line appears in red as a syntax error
    Debug.Print ((New Class1).Greeting)
End Sub

Where Class1 is a trivial class

Public Function Greeting()
    Greeting = "Hello world"
End Function

What is interesting is that VBA does allow the creation of an object on the fly when passing an argument thus...

Sub PassNewlyCreated()
    Bar New Class1
End Sub

Sub Bar(obj As Object)
    Debug.Print obj.Greeting
End Sub

So we can pull a trick here. If we define a function which simply passes an object on then we can get closer to the anonymous object syntax given at the top of this post. We'll call that function Anon() ...

Sub UseAnAnonymousObject()
    Debug.Print (Anon(New Class1).Greeting)
End Sub

Function Anon(obj As Object) As Object
    Set Anon = obj
End Function

Just some syntactic sugar for you there.

No comments:

Post a Comment