C# Dot Net Interview Preparation Part 14| Top 6 Frequently Asked Interview Questions and Answers
C# Dot Net Interview Preparation Part 13| Top 6 Frequently Asked Interview Questions and Answers

C# Dot Net Interview Preparation Part 14| Top 6 Frequently Asked Interview Questions and Answers


Question 79: What is the difference between == and .Equals() in C#?

Answer:

  • == compares values for value types and references for reference types (unless overridden).
  • .Equals() can be overridden for custom comparison.

Code Example:

string a = "hello";
string b = new string("hello".ToCharArray());

Console.WriteLine(a == b);        // True (compares values for strings)
Console.WriteLine(a.Equals(b));   // True (compares values)
        

Question 80: What is boxing and unboxing in C#?

Answer:

  • Boxing: Converting a value type to object.
  • Unboxing: Extracting the value type from the object.

Code Example:

int number = 42;          // Value type
object boxed = number;    // Boxing
int unboxed = (int)boxed; // Unboxing

Console.WriteLine(unboxed); // Output: 42
        

Question 81: What is the params keyword in C#?

Answer: It allows passing a variable number of arguments to a method.

Code Example:

void PrintNumbers(params int[] numbers)
{
    foreach (int number in numbers)
        Console.WriteLine(number);
}

PrintNumbers(1, 2, 3, 4);  // Output: 1 2 3 4
        

Question 82: What is the difference between const and readonly in C#?

Answer:

  • const: Compile-time constant, must be initialized where declared.
  • readonly: Runtime constant, can be initialized in constructor.

Code Example:

class Example
{
    public const int MyConst = 10;
    public readonly int MyReadonly;

    public Example(int value)
    {
        MyReadonly = value;
    }
}
        

Question 83: What is static class in C#?

Answer: A static class cannot be instantiated, and all its members must be static.

Code Example:

static class MathHelper
{
    public static int Add(int a, int b) => a + b;
}

int sum = MathHelper.Add(3, 5); // Output: 8
        

Question 84: What is the difference between throw and throw ex in exception handling?

Answer:

  • throw: Preserves the original stack trace.
  • throw ex: Resets the stack trace, making debugging harder.

Code Example:

try
{
    throw new Exception("Something went wrong");
}
catch (Exception ex)
{
    throw;     // Good practice
    // throw ex; // Avoid this
}
        

✅ Hashtags:

  • #DotNetLearners
  • #CodeWithCSharp
  • #CSharpFundamentals
  • #NetInterviewPrep
  • #TechTipsDaily
  • #BeginnerDotNet
  • #CodeSimplified
  • #LearnProgrammingFast
  • #CSharpInDepth
  • #TechCareersGuide


To view or add a comment, sign in

Others also viewed

Explore topics