Consider the following C# code. What will be printed when Main runs?
class MyClass { private int secret = 42; public int GetSecret() { return secret; } } class Program { static void Main() { MyClass obj = new MyClass(); System.Console.WriteLine(obj.GetSecret()); } }
Remember that private fields can be accessed inside the same class.
The private field secret is accessed inside MyClass through the public method GetSecret(). So, the output is 42.
Assume ClassA is in Assembly1 and ClassB is in Assembly2. ClassA has an internal method InternalMethod(). What happens if ClassB tries to call InternalMethod()?
public class ClassA { internal void InternalMethod() { System.Console.WriteLine("Hello from internal method"); } } public class ClassB { public void Call() { ClassA a = new ClassA(); a.InternalMethod(); } }
Internal members are accessible only within the same assembly.
The internal method is not accessible from another assembly, so the compiler prevents access.
Look at the code below. Why does it fail to compile?
class Example { private int value = 10; } class Derived : Example { void Show() { System.Console.WriteLine(value); } }
Think about how private members behave with inheritance.
Private members are only accessible within the class they are declared in, not in derived classes.
Choose the correct access modifier that allows a member to be accessed within the same assembly and also by derived classes outside the assembly.
Think about combining 'protected' and 'internal' access.
protected internal allows access within the same assembly and also to derived classes outside the assembly.
Analyze the code and determine what will be printed when Main runs.
public class Outer { private int x = 5; public class Inner { public void Print(Outer o) { System.Console.WriteLine(o.x); } } } class Program { static void Main() { Outer outer = new Outer(); Outer.Inner inner = new Outer.Inner(); inner.Print(outer); } }
Remember that nested classes can access private members of the outer class instance.
The nested class Inner can access private members of its containing class Outer through an instance.