Using C# or VB.NET collection in your VB6 Applications

28. August 2008 05:34 by Mrojas in General  //  Tags: , , , ,   //   Comments (0)

If you have some .NET code that you want to share with VB6, COM has always been a nice option. You just add couple of ComVisible tags and that's all.

But...

Collections can be a little tricky.

This is a simple example of how to expose your Collections To VB6.

Here I create an ArrayList descendant that you can use to expose your collections.
Just create a new C# class library project and add the code below.
Remember to check the Register for ComInterop setting.

 
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;

namespace CollectionsInterop
{
    
    [Guid("0490E147-F2D2-4909-A4B8-3533D2F264D0")]
    [ComVisible(true)]
    public interface IMyCollectionInterface 
    {

        int Add(object value);
        void Clear();
        bool Contains(object value);
        int IndexOf(object value);
        void Insert(int index, object value);
        void Remove(object value);
        void RemoveAt(int index);

        [DispId(-4)]
        System.Collections.IEnumerator GetEnumerator();
      
        [DispId(0)]
        [System.Runtime.CompilerServices.IndexerName("_Default")]
        object this[int index]
        {
            get;
        }
    }

    
    [ComVisible(true)]
    [ClassInterface(ClassInterfaceType.None)]
    [ComDefaultInterface(typeof(IMyCollectionInterface))]
    [ProgId("CollectionsInterop.VB6InteropArrayList")]
    public class VB6InteropArrayList : System.Collections.ArrayList, IMyCollectionInterface
    {

        #region IMyCollectionInterface Members


        // COM friendly strong typed GetEnumerator

        [DispId(-4)]
        public System.Collections.IEnumerator GetEnumerator()
        {
            return base.GetEnumerator();
        }



        #endregion
    }



    /// <summary>
    /// Simple object for example 
    /// </summary>
    [ComVisible(true)]
    [ClassInterface(ClassInterfaceType.AutoDual)]
    [ProgId("CollectionsInterop.MyObject")]
    public class MyObject
    {
        String value1 = "nulo";

        public String Value1
        {
            get { return value1; }
            set { value1 = value; }
        }
        String value2 = "nulo";

        public String Value2
        {
            get { return value2; }
            set { value2 = value; }
        }
    }


}
 
To test this code you can use this VB6 code. Remember to add a reference to this class library.
Private Sub Form_Load()
    Dim simpleCollection As New CollectionsInterop.VB6InteropArrayList
    Dim value As New CollectionsInterop.MyObject
    value.Value1 = "Mi valor1"
    value.Value2 = "Autre valeur"
    simpleCollection.Add value
    
    For Each c In simpleCollection
      MsgBox value.Value1
    Next
End Sub