Accesing an enum variable from a COM interface class

b_ioan 61 Reputation points
2022-12-13T14:06:25.937+00:00

Hello everyone!
In a .NET 6.0 library project I have the following old COM server code structure:

public interface IClass1  
{  
	public enum MyClass1Enum  
    {  
       C1E1,  
       C1E2  
    }  
}  
  
public interface IClass2  
{  
	public IClass1 C1 {get;set;}  
}  

All the classes are COM visible and have Guid attributes.
Now, a COM client will create a variable of type IClass2, fill up all his data and send it back to the server.
On the server side, I do not know how to get the enum data from the object received from the client.
if I try the following code in the server side, but the app crashed and close suddenly:

void ServerMethod(IClass2 dataCOM)  
{  
	var myEnum=dataCOM.C1.MyClass1Enum;  
}  

Any idea is much appreciated!!

Developer technologies | C#
Developer technologies | C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
{count} votes

Answer accepted by question author
  1. Michael Taylor 61,101 Reputation points
    2022-12-13T16:39:26.763+00:00

    An enum nested inside an interface in a COM interface? I've never seen that done in COM and don't even know if it is valid. In COM everything needs to have a GUID and be COM visible. You need to annotate your interface, enum and any other COM-related stuff with ComVisible.

    In regards to your code, that doesn't even look valid. MyClass1Enum is being used as a data member here but it is a type. In order to be valid MyClass1Enum would need to be a property of the IClass1 interface. What you posted as the original COM interface looks more like an IDL. So to get your sample code to compile it would need to look something like this.

       public interface IClass1  
       {  
          MyClass1Enum MyClass1Enum { get; set; }  
       }  
         
       public enum MyClass1Enum  
       {  
       }  
         
       public interface IClass2  
       {  
            IClass1 C1 {get;set;}  
       }  
    

    Note also that the COM server side needs to implement these same rules. Additionally since C1 is settable then the COM server needs to either ensure the property is set or the calling code needs to set it.

    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.