C# Dot Net Interview Preparation Part 7 | Top 6 Frequently Asked Interview Questions and Answers
Question 37: What is the difference between a struct and a class in C#?
Answer:
Code Example:
struct MyStruct
{
public int Value;
}
class MyClass
{
public int Value;
}
var struct1 = new MyStruct { Value = 10 };
var class1 = new MyClass { Value = 10 };
// Modifying struct1 won't affect copies.
Question 38: What is a static class in C#?
Answer: "A static class cannot be instantiated and can only contain static members (fields, methods, properties)."
Code Example:
public static class MathHelper
{
public static int Add(int a, int b) => a + b;
}
int result = MathHelper.Add(5, 3); // Output: 8
Question 39: What is the purpose of GC.Collect() in .NET?
Answer: "GC.Collect() forces garbage collection, clearing unused objects from memory. However, it's better to rely on automatic garbage collection for efficiency."
Code Example:
class Program
{
static void Main()
{
// Allocate memory
var largeArray = new int[10000];
GC.Collect(); // Explicitly invoke garbage collection
}
}
Recommended by LinkedIn
Question 40: What is the difference between Array and ArrayList in C#?
Answer:
Code Example:
int[] numbers = new int[3] { 1, 2, 3 }; // Array
ArrayList list = new ArrayList();
list.Add(1);
list.Add("String"); // ArrayList (mixed types)
Question 41: What is a thread in .NET, and how do you create one?
Answer: "A thread is the smallest unit of execution in .NET. Multiple threads can run simultaneously for better performance."
Code Example:
using System.Threading;
Thread thread = new Thread(() => Console.WriteLine("Thread started!"));
thread.Start();
Question 42: What is the difference between public, private, protected, and internal access modifiers?
Answer:
Access Modifier Description Public Accessible everywhere. Private Accessible only within the containing class. Protected Accessible within the containing class and derived classes. Internal Accessible within the same assembly.
Code Example:
class MyClass
{
public string PublicProperty { get; set; }
private int PrivateProperty { get; set; }
protected double ProtectedProperty { get; set; }
internal string InternalProperty { get; set; }
}
Hashtags for LinkedIn/YouTube Video: