Search

Drop Down MenusCSS Drop Down MenuPure CSS Dropdown Menu

Wednesday, May 17, 2023

Top 30 C# Static Class, Method, and Variable Interview Questions

Static classes are a powerful feature in C# that provide a convenient way to organize utility functions, common functionality, and shared data. Understanding the concept and advantages of static classes is essential for every C# developer. In this article, we will dive deep into the world of static classes top 30 C# interview question


Top 30 C# Static Class, Method, and Variable Interview Questions


1. What is a static class in C#?

A static class is a class that cannot be instantiated, and all of its members (methods, properties, fields) must be static. It is commonly used to provide utility functions or constants.

2. Can a static class be inherited in C#?

  No, a static class cannot be inherited. It is sealed by default, meaning it cannot be used as a base class for other classes.

3. What is a static constructor in C#?

 A static constructor is a special constructor in a class that is used to initialize static members of the class. It is called automatically before the first use of any static members in the class.

4. How is a static constructor different from an instance constructor?

A static constructor is used to initialize static members of a class and is called automatically by the runtime. It does not take any parameters and cannot be called explicitly. In contrast, an instance constructor is used to initialize instance members of a class and is called when an object of the class is created.

5. What is a static variable in C#?

A static variable is a variable that belongs to the class itself, rather than to any specific instance of the class. It is shared among all instances of the class and retains its value across multiple invocations.

6. How do you access a static variable in C#?

 A static variable can be accessed using the class name followed by the variable name, without creating an instance of the class.

7. What is an extension method in C#?

An extension method allows you to add new methods to existing types without modifying their source code. It is defined as a static method in a static class and is called as if it were an instance method of the extended type.

8. How do you define an extension method in C#?

To define an extension method, create a static class and define a static method within it. The first parameter of the method should have the `this` keyword followed by the type being extended. This tells the compiler which type the method is extending.

9. How are extension methods different from regular static methods?

Extension methods are called as if they were instance methods of the extended type, even though they are defined as static methods. This allows for a more fluent and natural syntax. Regular static methods, on the other hand, are called directly on the class they belong to.

10. What are some common use cases for extension methods?

Extension methods are often used to add functionality to existing classes or interfaces, especially when you don't have access to modify the source code of those classes. They are commonly used for adding utility methods or implementing additional behaviors for built-in types or third-party libraries.

11. Write a C# code snippet to demonstrate the usage of a static class.

csharp

public static class MathUtils

{

    public static int Add(int a, int b)

    {

        return a + b;

    }

}


// Usage:

int result = MathUtils.Add(5, 10);

Console.WriteLine(result);  // Output: 15

12. Write a C# code snippet to show how a static constructor is used.

public class MyClass

{

    public static int Counter { get; private set; }


    static MyClass()

    {

        Counter = 0;

    }


    public MyClass()

    {

        Counter++;

    }

}


// Usage:

Console.WriteLine(MyClass.Counter);  // Output: 0


MyClass obj1 = new MyClass();

Console.WriteLine(MyClass.Counter);  // Output: 1


MyClass obj2 = new MyClass();

Console.WriteLine(MyClass.Counter);  // Output: 2

13. Write a C# code snippet to demonstrate the usage of a static variable.

public class Counter

{

    public static int Count { get; private set; }


    public Counter()

    {

        Count++;

    }

}


// Usage:

Console.WriteLine(Counter.Count);  // Output: 0


Counter obj1 = new Counter();

Console.WriteLine(Counter.Count);  // Output: 1


Counter obj2 = new Counter();

Console.WriteLine(Counter.Count);  // Output: 2

14. Write a C# code snippet to define an extension method for the `string` class that counts the number of words in a string.

public static class StringExtensions

{

    public static int WordCount(this string str)

    {

        if (string.IsNullOrEmpty(str))

            return 0;


        string[] words = str.Split(new[] { ' ', '\t', '\n' }, StringSplitOptions.RemoveEmptyEntries);

        return words.Length;

    }

}


// Usage:

string text = "Hello, how are you?";

int count = text.WordCount();

Console.WriteLine(count);  // Output: 4

15. Write a C# code snippet to demonstrate the usage of an extension method for the `List<T>` class that shuffles the elements randomly.

public static class ListExtensions

{

    private static readonly Random random = new Random();


    public static void Shuffle<T>(this List<T> list)

    {

        int n = list.Count;

        while (n > 1)

        {

            n--;

            int k = random.Next(n + 1);

            T value = list[k];

            list[k] = list[n];

            list[n] = value;

        }

    }

}


// Usage:

List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };

numbers.Shuffle();

Console.WriteLine(string.Join(", ", numbers));  // Output: (random order of numbers)

16. Can you have a static method in a normal (non-static) class in C#?

Yes, you can have static methods in a normal class. Static methods belong to the class itself rather than to instances of the class.

17.  How do you define a static method in a normal class in C#?

 To define a static method in a normal class, use the `static` modifier before the method declaration. It can be accessed using the class name followed by the method name, without creating an instance of the class.

18. What is a static variable in a normal class?

A static variable in a normal class is a variable that is shared among all instances of the class. It retains its value across multiple invocations and is accessed using the class name followed by the variable name.

19.  How do you define a static variable in a normal class in C#?

To define a static variable in a normal class, use the `static` modifier before the variable declaration. It is typically initialized when the class is first accessed and retains its value throughout the program's execution.

20. Can you overload static methods in a normal class in C#?

Yes, you can overload static methods in a normal class. Overloading allows you to define multiple methods with the same name but different parameters. The appropriate method is called based on the arguments provided at the call site.

21. How is static method overloading resolved in C#?

Static method overloading is resolved at compile-time based on the static type of the variable or expression used to invoke the method. The compiler determines the most appropriate method to call based on the number, types, and order of the arguments.

22.  Can a static class inherit from another class in C#?

No, a static class cannot inherit from another class in C#. Static classes are sealed by default, meaning they cannot be used as a base class for other classes.

23. Can a normal (non-static) class inherit from a static class in C#?

 No, a normal class cannot inherit from a static class in C#. Static classes are sealed and cannot be used as a base class.

24.  What are some common use cases for static methods and variables in a normal class?

Static methods and variables in a normal class are often used for utility functions, helper methods, or to maintain shared data among instances of the class. They can provide common functionality that is not specific to any particular instance.

25. What are some advantages of using a static class in C#?

Some advantages of using a static class include:

  1.      - Easy access to utility methods or common functionality without needing to create instances of the class.
  2.      - Improved performance since there is no overhead of object creation.
  3.      - Ability to hold shared data through static variables.
  4.      - Convenient organization of related methods and functionality.

26. Can a static class implement an interface in C#?

No, a static class cannot implement an interface. Interfaces define a contract for instance members, but a static class cannot be instantiated, and all of its members are static.

27. Is it possible to use dependency injection with a static class in C#?

 No, dependency injection is typically used with instance-based objects, and it does not directly apply to static classes. Static classes often provide utility functions or common functionality, and they are not designed to be instantiated or managed through dependency injection.

28. Can a static class have instance members in C#?

No, a static class cannot have instance members. All members (methods, properties, fields) of a static class must be static.

29. Can a static class be serialized in C#?

No, a static class cannot be serialized. Serialization is the process of converting an object into a stream of bytes to store or transmit, but static classes cannot be instantiated, so they cannot be serialized.

30. How can you unit test code that depends on a static class in C#?

  • Testing code that depends on a static class can be challenging. Some approaches to handle this include:
  •  Extracting the logic from the static class into a non-static class or interface, and then mocking or stubbing that interface during testing.
  •  Using a mocking framework that can intercept calls to static members and provide custom behavior for testing purposes.
  •  Creating test-specific overrides for the static class using techniques like shimming or using frameworks that allow the interception of static method calls.

31. Can a static class contain a constructor in C#?

No, a static class cannot contain an instance constructor. Static classes are not instantiated, so they do not require constructors. However, they can contain a static constructor that is used to initialize static members of the class.

32. What is the thread-safety concern when using a static class in a multi-threaded environment?

 When using a static class in a multi-threaded environment, thread safety can be a concern. Since static classes are shared among all threads, concurrent access to shared data or resources within the static class can lead to race conditions or other synchronization issues. Proper synchronization techniques such as locks, mutexes, or thread-safe data structures should be used to ensure thread safety when accessing shared data in a static class.

No comments:

Post a Comment