简体   繁体   中英

internal class access c#

This maybe a very simple question! But I have been scratching my head for an hour now! I have two files as below:

  1. Assembly1.cs
  2. Program.cs

I thought when I use internal keyword before a class name I won't be able to instantiate it in other classes, right?

https://msdn.microsoft.com/en-us/library/7c5ka91b.aspx

But why am I not getting an error message for this here? I maybe missing something very obvious here.

// Assembly1.cs
namespace InternalTest
{
    internal sealed class BaseClass 
    {
        public static int intM = 0;
    }
}


// Program.cs
using System;

namespace InternalTest
{
    class Program
    {
        static void Main(string[] args)
        {

            var myBase = new BaseClass();

            Console.ReadKey();

        }
    }
}

Internal means class is accessible within the assembly.Above class is in same assembly hence no error.If you want to see the error then follow below step

1) Create Library project

2) Create Base Class in that project

3) Create Console project

4) Add reference of first project dll

5) Now try to create instance, you will see the error

Additional Info

If you want to access internal members in your console project then add below attribute in AssemblyInfo.cs of Library project

[assembly:InternalsVisibleTo("[AssemblyNameOfConsoleProject]")] 

Because both classes are on the same namespace.

//InternalTest
namespace InternalTest
{
internal sealed class BaseClass 
{
    public static int intM = 0;
}
}

//the same here InternalTest
namespace InternalTest
{
class Program
{
    static void Main(string[] args)
    {
    }
}
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM