Question

using System.IO;
using System;
using Assembly2;

// DLL 1
namespace Assembly1
{
   class class1 : class2
   {
      static void Main()
      {
         Console.WriteLine(new class2().sample); //Cannot access. Protected means --> accessible to the derived classes right ? (But, note that this is a different assembly. Does not work because of that ?)
      }
   }
}

// DLL 2
namespace Assembly2
{
    public class class2
    {
      protected string sample = "Test";
    }
}

In the above simple code,

I cannot access the string sample in assembly 2 though I am deriving from class2

From MSDN: 

The type or member can be accessed only by code in the same class or struct, or in a class that is derived from that class.

Does this definition stand only for the same assembly or can the protected members be accessed across assemblies ?

Was it helpful?

Solution

You can access the protected member from a different assembly, but only within a subclass (as normal for protected access):

// In DLL 1
public class Class3 : class2
{
    public void ShowSample()
    {
        Console.WriteLine(sample);
    }
}

Note that your current code would fail even if the classes were in the same assembly.

OTHER TIPS

A protected member of a base class is accessible in a derived class only if the access occurs through the derived class type.

class class1:class2    
{    
      static void Main()
      {
         Console.WriteLine(new class1().sample);
      }
 }

now above code will run.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top