C# Interview Questions and Answers for 10 years experience

C# Interview Questions (10 Years Experience)
  1. What are the different types of access modifiers in C#? Explain their usage with examples.

    • Answer: C# offers several access modifiers: `public`, `private`, `protected`, `internal`, `protected internal`. `public` members are accessible from anywhere. `private` members are only accessible within the same class. `protected` members are accessible within the same class and derived classes. `internal` members are accessible within the same assembly. `protected internal` members are accessible within the same assembly and derived classes.
      Example: public class MyClass { public int PublicVar; // Accessible everywhere private int PrivateVar; // Accessible only within MyClass protected int ProtectedVar; //Accessible in MyClass and derived classes internal int InternalVar; //Accessible within the same assembly protected internal int ProtectedInternalVar; //Accessible within the same assembly and derived classes }
  2. Explain the difference between `ref` and `out` parameters.

    • Answer: Both `ref` and `out` parameters pass variables by reference, modifying the original variable. However, `ref` requires the variable to be initialized before being passed, while `out` does not. The `out` parameter signals that the method will assign a value to it.
      Example: public void MyMethod(ref int x, out int y) { x++; // Modifies the original x y = 10; // Assigns a value to y }
  3. What is garbage collection in C#? How does it work?

    • Answer: Garbage collection is an automatic memory management feature in C#. It reclaims memory occupied by objects that are no longer referenced by the program. The garbage collector periodically runs, identifying unreachable objects and freeing their memory. It employs techniques like mark-and-sweep and compaction to optimize memory usage. While generally automatic, you can influence its behavior using methods like `GC.Collect()` (though generally discouraged).
  4. Explain the concept of delegates and events in C#. Provide a practical example.

    • Answer: Delegates are type-safe function pointers. They allow you to pass methods as arguments to other methods. Events are a messaging mechanism built upon delegates; they allow one object to notify other objects when something significant happens.
      Example: public delegate void MyDelegate(string message); public class Publisher { public event MyDelegate MyEvent; public void Publish(string message) { if (MyEvent != null) { MyEvent(message); } } } public class Subscriber { public void HandleEvent(string message) { Console.WriteLine("Received: " + message); } }

Thank you for reading our blog post on 'C# Interview Questions and Answers for 10 years experience'.We hope you found it informative and useful.Stay tuned for more insightful content!