I need IMessage Interface. In C# I could write
CDO.Message oMsg = new CDO.Message(); // ok
but when I try to do this in F#
let oMsg = new CDO.Message()
I get an error message:
'new' cannot be used on interface types. Consider using an object expression '{ new ... with ... }' instead.
How to solve this problem?
A COM object is an instance of a coclass in memory. Note that a COM "class" is not the same as a C++ "class", although it is often the case that the implementation of a COM class is a C++ class. A COM server is a binary (DLL or EXE) that contains on or more coclasses.
An object expression is an expression that creates a new instance of a dynamically created, anonymous object type that is based on an existing base type, interface, or set of interfaces.
You need to use the version that has the "Class" added to the interface name:
open System
[<EntryPoint>]
[<STAThread>]
let main argv =
let oMsg = new CDO.MessageClass()
oMsg.Subject <- "Hello World"
Console.WriteLine(oMsg.Subject)
Console.ReadLine() |> ignore
0
Note: I also explicitly had to add a reference to Microsoft ActiveX Data Objects 6.0 Library
to the project to make the object instantiation work.
In case you want to use the specific interface and not the Co-Class (as proposed by Hans Passant), use this version that casts the created Co-Class to the interface, thereby returning a pointer to the actual interface.
open System
[<EntryPoint>]
[<STAThread>]
let main argv =
let oMsg = upcast new CDO.MessageClass() : CDO.IMessage
oMsg.Subject <- "Hello World"
Console.WriteLine(oMsg.Subject)
Console.ReadLine() |> ignore
0
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With