How to expose base class while keeping derived ones internal

264 Views Asked by At

Hello i have the following problem:

I have a struct

public struct Cell
{
   public Node Value;
   public static implicit Cell(Node value)=>new Cell(value); //can't since node less accesible then cell
}

This struct Cell contains a property of type Node which is an abstract base class and currently is internal with all its derived classes.What i need is to somehow make the Cell struct accesible for other developers so that they can extract the value of the Node without knowing the Node derived class.

        internal abstract  class Node{
                internal class ANode:Node{
                    public byte[] internalValue;
                }
                internal class BNode:Node{
                    public int internalValue;
                }
         }

How can i achieve this? The cell is exposed to outside and so should the abstract base class Node.The user should be able to implicit cast from Node to Cell.

Current approach
What i have tried so far is define an interface IRaw for Node that extracts the content from the Node derived classes.The explicit implementation is a virtual method ,overloaded in the derived classes.

    interface IRaw{
       byte[] GetRaw();
    }

    internal abstract class Node:IRaw
    {
      byte[] IRaw.GetRaw()=>this.GetRaw();
      protected virtual byte[] GetRaw(){ ....}
    }

    internal class ANode:Node
    {
      protected override byte[] GetRaw()
      {
        .....
      }
    }

The problem in the above approach is that i can not pass the IRaw as argument in the Cell constructor with the error code: user defined conversions to or from an interface are not allowed.

 public struct Cell
        {
           public IRaw Value;
           public static implicit Cell(IRaw value)=>new Cell(value);
        }

Any suggestions ?I practically need a "Bridge" between the Cell which is public and the contents of Node which are internal.

1

There are 1 best solutions below

2
Sefe On BEST ANSWER

You can simply make Node public and keep its derived classes internal. Unrelated to that, you should think about not deriving Node in nested classes for better maintainability:

public abstract class Node {
}

internal class ANode : Node {
    public byte[] internalValue;
}

internal class BNode : Node {
    public int internalValue;
}

If you want to be able to create instances of ANode and BNode from external assemblies, you can use an abstract factory:

public static class NodeFactory {
    public Node CreateNode(byte[] value) {
        return new ANode { internalValue = value };
    }

    public Node CreateNode(int value) {
        return new BNode { internalValue = value };
    }
}