Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access 'Internal' classes with C# interactive

Using the C# interactive console in VS2015, i want to access properties and classes marked as internal. Usually, this is done by adding the InternalsVisibleAttribute to the project in question. Ive tried adding csc.exe as a 'friend' assembly, but i still have the access problems.

  1. Is this the correct approach to access internal class members via the C# interactive console?
  2. If it is, what dll/exe do i need to make the internals visible to?
like image 732
richzilla Avatar asked Jul 26 '16 09:07

richzilla


1 Answers

This is possible, but I am not sure why you need to do this. The type is internal for a reason. Here is how it can be done -

Create a console application with following code -

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("Hello World!");
    }
}

Add the internal class -

internal class MyClass
{
    internal string MyMethod()
    {
        return "Hello world!";
    }
}

Build your solution. In your c# interactive window -

>#r "C:\Users\...\Project.dll"
>using System;
>using System.Reflection;
>Assembly assembly = >Assembly.LoadFrom("C:\Users\...\Project.dll");
> Object mc = assembly.CreateInstance("AccessInternal.MyClass");
> Type t = mc.GetType();
> BindingFlags bf = BindingFlags.Instance | BindingFlags.NonPublic;
> MethodInfo mi = t.GetMethod("MyMethod", bf);
> string result = (string)mi.Invoke(mc, null);
> Console.WriteLine(result);
Hello world!
>

Note : Given that this is c# interactive window, it does not load the dependent objects of your target component, i.e. if your assembly is referring to other assemblies that are being referred to in your internal method, then c# interactive will fail in executing method unless it has access to those assemblies and can load them.

like image 145
Amogh Sarpotdar Avatar answered Sep 30 '22 01:09

Amogh Sarpotdar