1. Inheritance in C# with examples
Inheritance in C# is a mechanism where one class (the child or derived class) inherits the properties, methods, and behavior of another class (the parent or base class).
Key Points:
1. Base Class: Animal defines common functionality (e.g., Eat method, Name property).
2. Derived Class: Dog inherits from Animal and adds its own functionality (e.g., Bark method).
3. Accessing Members: The derived class can access both its own members and the members of the base class.
Notes:
• Use the : symbol to denote inheritance (class Derived : Base).
• C# supports single inheritance (a class can inherit from only one base class) but allows multiple interfaces to be implemented.
• The base keyword can be used in the derived class to access members of the base class explicitly.
//Example Code
using System;
namespace InheritanceExample
{
// Base class
class Animal
{
public string Name { get; set; }
public void Eat()
{
Console.WriteLine($"{Name} is eating.");
}
}
// Derived class
class Dog : Animal
{
public void Bark()
{
Console.WriteLine($"{Name} is barking.");
}
}
class Program
{
static void Main(string[] args)
{
// Create an object of the derived class
Dog myDog = new Dog();
// Access base class members
myDog.Name = "Buddy";
myDog.Eat();
// Access derived class members
myDog.Bark();
}
}
}
//Output:
//Buddy is eating.
//Buddy is barking.
2. What are Delegates and Events in C#?
Answer:
Delegates: A delegate is a type-safe function pointer that allows you to pass methods as parameters. It can be used to define callback methods, event handlers, or implement asynchronous programming.
Example:
delegate void MyDelegate(string message);
public void PrintMessage(string message) {
Console.WriteLine(message);
}
MyDelegate del = new MyDelegate(PrintMessage);
del("Hello World");
Events: An event is a mechanism that allows an object to notify other objects when something happens. It is typically used in the observer pattern. Events are based on delegates, and subscribers can register to receive notifications when an event is raised.
Example:
public class EventPublisher {
public event EventHandler MyEvent;
public void TriggerEvent() {
MyEvent?.Invoke(this, EventArgs.Empty);
}
}
3. What is the difference between value types and reference types in C#?
Answer:
Value Types: These types hold data directly. Examples include int, float, char, and struct. When assigned to another variable, a copy of the data is made.
Reference Types: These types store references (pointers) to the actual data. Examples include class, string, array, and delegate. When assigned to another variable, both variables point to the same object in memory.
Key differences:
Value types are stored on the stack and have a fixed size, while reference types are stored on the heap and can have dynamic sizes.
Value types cannot be null, while reference types can.
4. What is the purpose of the using statement in C#?
Answer: The using statement is used to import namespaces or to define a scope for an object that implements IDisposable to ensure it is properly disposed of after use. When working with resources such as files, network connections, or database connections, the using statement ensures that the resources are released automatically.
Example (importing namespaces):
using System;
using System.Linq;
Example (for disposing resources):
using (var reader = new StreamReader("file.txt"))
{
string content = reader.ReadToEnd();
}
The StreamReader object will be automatically disposed of when it goes out of scope.
5. What is the difference between abstract class and interface in C#?
Answer:
abstract class: Can have both abstract methods (without implementation) and methods with implementation. A class can inherit only one abstract class (single inheritance).
interface: Can only declare method signatures and properties (no implementation). A class can implement multiple interfaces (multiple inheritance).
Key differences:
A class can inherit only one abstract class but can implement multiple interfaces.
abstract classes can have fields, constructors, and non-abstract methods, while interfaces can only have method signatures (until C# 8.0, where default interface methods were introduced).
6. What is the difference between public, private, protected, and internal access modifiers in C#?
Answer:
public: The member is accessible from any code in the same assembly or another assembly.
private: The member is accessible only within the same class or struct.
protected: The member is accessible within the same class and by derived classes.
internal: The member is accessible only within the same assembly (project).
protected internal: The member is accessible within the same assembly and by derived classes.
private protected: The member is accessible only within the same class and by derived classes within the same assembly.
7. What is the difference between string and StringBuilder in C#?
Answer:
string: In C#, string is immutable, which means any operation that modifies a string results in the creation of a new string object. This can lead to performance issues when dealing with large or numerous string manipulations.
StringBuilder: StringBuilder is mutable, meaning that it allows modifications to the same string object, which improves performance when doing repetitive string manipulations (e.g., concatenation in loops).
// Inefficient for loops with string concatenation:
string str = "";
for (int i = 0; i < 1000; i++) {
str += "Hello";
}
// Efficient with StringBuilder:
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 1000; i++) {
sb.Append("Hello");
}
8. What is the difference between ref and out parameters in C#?
Answer:
ref: The ref keyword indicates that a parameter is passed by reference. The variable passed must be initialized before being passed into the method.
out: The out keyword also passes a parameter by reference but does not require the variable to be initialized before passing it to the method. The method must assign a value to the out parameter before it exits.
9. What are the main features of C#?
Answer: Some of the key features of C# include:
Object-Oriented: Supports encapsulation, inheritance, and polymorphism.
Type-Safety: Ensures that types are used correctly.
Garbage Collection: Automatically manages memory to avoid memory leaks.
Multithreading: Provides support for creating and managing multiple threads of execution.
LINQ (Language Integrated Query): Enables querying of various data sources like arrays, collections, and databases in a consistent and readable way.
Cross-platform: With .NET Core, C# code can run on multiple platforms (Windows, Linux, macOS).
10. What is C#?
Answer: C# (pronounced "C-sharp") is a modern, object-oriented programming language developed by Microsoft as part of its .NET framework. It is designed for building a wide range of applications, from web to desktop and mobile applications. C# is known for its simplicity, type safety, and support for modern programming paradigms like object-oriented programming (OOP), asynchronous programming, and LINQ.