Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to make all internal classes visible to another assembly in C# with some configuration?

I know that is possible change the visibility with:

using System.Runtime.CompilerServices;

[assembly: InternalsVisibleTo("UnitTests")]

namespace Foobar
{
    internal class Foo
    {
      //...
    }
}

So my test project can create the test for the class Foo. The problem is that I have a lot of internal classes and I don't want to dirty them with that assembly expression. Is there another way of doing this InternalsVisibleTo("UnitTests") for the whole project?

like image 383
dreinoso Avatar asked Nov 21 '16 14:11

dreinoso


People also ask

Can I use an internal class in another project?

If a class or member is internal it´s ment to be used only within a given assembly. If you need access from outside the assembly make the class public.

What is an assembly that can access the internal members of another assembly called?

A friend assembly is an assembly that can access another assembly's internal (C#) or Friend (Visual Basic) types and members.

Can internal class have public methods?

The short answer is that it doesn't matter. Public methods of an internal class are internal. To the compiler, the internal/public method distinction only matters for public classes.

Can we create instance for an internal class?

class OuterClass { ... class InnerClass { ... } } An instance of InnerClass can exist only within an instance of OuterClass and has direct access to the methods and fields of its enclosing instance. To instantiate an inner class, you must first instantiate the outer class.


1 Answers

The [InternalsVisibleTo] attribute is an assembly-level attribute, meaning that if you define it once, it already applies to the entire assembly.

So that line you show only needs to be included only once in your project to apply to all internal types.

I'd recommend moving it to where the other assembly-level attributes are specified: in the AssemblyInfo.cs file in the Properties folder of the project.

like image 185
CodeCaster Avatar answered Sep 22 '22 07:09

CodeCaster