Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I access to an internal static class from another assembly?

Tags:

c#

I've the following situation:

1) I have an internal static class where my software initialize a form 2) I would like to get the instance of this form to use for other reasons.

Example of code:

Class1:

 namespace x {
       internal static class Program {
         private static Form mainx;
         private static void Main() {
           .....
           .....
           mainx=new Form(.....);
           Application.run(mainx);
         }
       }
    }

Class2: I want to use one thing like this:

Form1 try=Program.mainx;

How can i do it?

like image 265
Silvio S. Avatar asked Feb 18 '14 12:02

Silvio S.


2 Answers

If both assemblies are signed, you can use the InternalsVisibleToAttribute to expose internal members of an assembly to another.

I often use this to enable unit testing of internal classes without having to expose them as public.

like image 88
Trevor Pilley Avatar answered Oct 05 '22 23:10

Trevor Pilley


You could mark the assembly with the internal class as a friend assembly on the other assembly, with the attribute InternalsVisibleTo. You will find more informations about this on the MSDN.

You need to add this line to your AssemblyInfo class (in the Properties folder), i.e. on the last line. This must be added in the project where you have declared the internal class.

[assembly:InternalsVisibleTo("NameOfOtherAssembly")]

If you with to retrieve the mainx property of your Program class, you need to make a visible (public or internal) getter on your class:

internal static class Program
{
    private static Form mainx;

    ...

    public static Form GetForm()
    {
        return mainx;
    }
}

In your second class, you should then be able to get the form by calling GetForm():

Form1 try=Program.GetForm();
like image 37
Kevin Brechbühl Avatar answered Oct 06 '22 00:10

Kevin Brechbühl