VarBstrFromDisp (oleaut32)
Last changed: -80.61.160.102

.
Summary
Handy function Invoke the default value(s) on a ComObject reference within C#/VB.NET. The full code to retrieve DispId(0) (Default Value) from a Dispatch interface is ugly. This pinvoke is elegant and quick. Also supported on 64 bit of course.

C# Signature:

[DllImport("oleaut32.dll", SetLastError=false, ExactSpelling=true)]
static extern int VarBstrFromDisp(IntPtr Disp, int lcid, int dwFlags, [MarshalAs(UnmanagedType.BStr)] out string pbstrOut);

VB Signature:

Declare Function VarBstrFromDisp Lib "oleaut32.dll" (Byval Disp as IntPtr, Byval lcid As Integer, Byref pbstrOut as String) As Integer

User-Defined Types:

None.

Alternative Managed API:

There is no alternative API in .NET except for Dispatch Invoke the default value (DispId == 0)

However, you could use the dynamic keyword if you do know the name of the default Dispatch property, such as 'Value' or 'Text'. But if you don't know the default property, the IDispatch Invoke() method comes in, which is ugly. Whynot have OleAut32.dll do it for you?

Notes:

The sample cannot be used on DCOM (remote COM). It is not tested.

Tips & Tricks:

Please add some!

Sample Code:

object pComObject = rs.Fields[0]; // ADODB COM stuff just to illustrate how it works. Normally, use a typelibrary or the dynamic keyword

if (Marshal.IsComObject(pComObject)) // shows as System.__ComObject

{

   string pbstrOut;
   int hr = VarBstrFromDisp(Marshal.GetIDispatchForObjectInContext(pComObject), Thread.CurrentThread.CurrentCulture.LCID, 0, out pbstrOut);
   if (hr != 0)
   {
       Marshal.ThrowExceptionForHR(hr);
   }
}


Documentation