Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access to internal classes from another project

Tags:

c#

internal

I'm wondering if it's possible to access internal class variables from other project in c#. I know that is impossible in regular use, I explain it below.

I have one project (P1 [class library]) containing those classes...

internal class Settings
{
    public static long size {get;set;}

    public static DoSomethingInternalOnly()
    {
    }
}

public class Program
{
    public static Main()
    {

    }
}

... and another one (P2) containing:

public class Program
{
    public static Main()
    {
        //P1.CopyOfSettings.size = 2048; ???
    }
}

In Settings class I store internal variables (and methods) for app which cannot be visible from other projects. But those settings need to be passed somehow from P2 to P1 so I need second class "Settings2" in P2 containing the same variables (variables only!) as "Settings" with public keyword.

I feel that creating several classes containing the same variables is a waste of time and makes code unreadable. Is there better way to accomplish this?

like image 745
Adam Mrozek Avatar asked Feb 03 '14 12:02

Adam Mrozek


People also ask

Can I use an internal class in another project?

Yes it is, using InternalsVisibleTo, but I would only recommend doing this for Unit Test projects. Otherwise, you should extract a common interface, make it public and put it in a separate assembly that can be references by both projects.

How do you call an internal method from another assembly?

internal: The type or member can be accessed by any code in the same assembly, but not from another assembly. You can not use internal classes of other assemblies, the point of using internal access modifier is to make it available just inside the assembly the class defined.

Can internal class have public members?

internal is the default if no access modifier is specified. Struct members, including nested classes and structs, can be declared public , internal , or private .


2 Answers

You can use the InternalsVisibleTo attribute and provide the name of a specific assembly that can see the internal types in your assembly.

That being said.. I think you are bordering on over-designing this. If the Settings class belongs only to Assembly A... don't put it in Assembly B... put it in Assembly A.

like image 198
Simon Whitehead Avatar answered Sep 21 '22 13:09

Simon Whitehead


Yes it is, using InternalsVisibleTo, but I would only recommend doing this for Unit Test projects.

Otherwise, you should extract a common interface, make it public and put it in a separate assembly that can be references by both projects.

You could make all the properties of the interface read-only so that the consumer cannot change them.

like image 44
Matthew Watson Avatar answered Sep 17 '22 13:09

Matthew Watson