Search code examples
c#class

How can I access an internal class from an external assembly?


Having an assembly which I cannot modify (vendor-supplied) which have a method returning an object type but is really of an internal type.

How can I access the fields and/or methods of the object from my assembly?

Keep in mind that I cannot modify the vendor-supplied assembly.

In essence, here's what I have:

From vendor:

internal class InternalClass
  public string test;
end class

public class Vendor
  private InternalClass _internal;
  public object Tag {get{return _internal;}}
end class

From my assembly using the vendor assembly.

public class MyClass
{
  public void AccessTest()
  {
    Vendor vendor = new Vendor();
    object value = vendor.Tag;
    // Here I want to access InternalClass.test
  }
}

Solution

  • Without access to the type (and no "InternalsVisibleTo" etc) you would have to use reflection. But a better question would be: should you be accessing this data? It isn't part of the public type contract... it sounds to me like it is intended to be treated as an opaque object (for their purposes, not yours).

    You've described it as a public instance field; to get this via reflection:

    object obj = ...
    string value = (string)obj.GetType().GetField("test").GetValue(obj);
    

    If it is actually a property (not a field):

    string value = (string)obj.GetType().GetProperty("test").GetValue(obj,null);
    

    If it is non-public, you'll need to use the BindingFlags overload of GetField/GetProperty.

    Important aside: be careful with reflection like this; the implementation could change in the next version (breaking your code), or it could be obfuscated (breaking your code), or you might not have enough "trust" (breaking your code). Are you spotting the pattern?