Search code examples
c#classinternal

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();

        }
    }
}

Solution

  • 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]")]