Guilherme Serafina
Guilherme Serafina

Reputation: 155

Cannot cast list of internal class from another assembly in C#

I'm using a function from an external assembly that returns an object which is a list of an internal class and I cannot find a way to cast it in my code.

Code in the external assembly:

namespace AssemblyNamespace
{
    internal class InternalClass
    {
        protected internal byte b;
        protected internal int i;
    }

    public class PublicClass
    {
        public object PublicMethod()
        {
             return new List<InternalClass>();
        }
    }
}

My code:

using AssemblyNamespace;

static void Main()
{
    PublicClass P = new PublicClass();
    object obj = new object();

    obj = P.PublicMethod();

    // Is it possible to cast obj?
}

Is it possible to cast obj through reflection or something else? I took a look at question C# - How to access internal class from external assembly but could not find a way to use their suggestions.

Upvotes: 3

Views: 657

Answers (1)

mm8
mm8

Reputation: 169400

You should not expose an internal type from a public API...and you are returning an empty list from PublicMethod() so there is no InternalClass object to access.

But if the PublicMethod() actually returns an InternalClass object...:

public class PublicClass
{
    public object PublicMethod()
    {
        return new List<InternalClass>() { new InternalClass() { b = 10 } };
    }
}

...you could access its fields through reflection like this:

static void Main()
    {
        PublicClass P = new PublicClass();
        System.Collections.IList list = P.PublicMethod() as System.Collections.IList;
        object internalObject = list[0];
        FieldInfo fi = internalObject.GetType().GetField("b", BindingFlags.NonPublic | BindingFlags.Instance);
        byte b = (byte)fi.GetValue(internalObject);
        Console.WriteLine(b);
    }

The above sample code will print "10", i.e. the value of the byte "b" field of the InternalClass object returned from the PublicMethod(), to the Console.

Upvotes: 3

Related Questions