NET Interview Questions for 2025

author image Hirely
at 09 Jan, 2025

Question: What is LINQ in .NET?

Answer:

LINQ (Language Integrated Query) is a feature in .NET that allows developers to write SQL-like queries directly in C# (or other .NET languages) to query collections of data such as arrays, lists, or databases. It provides a unified way of querying data from different sources, such as in-memory collections, XML, relational databases, or other data stores, without having to write raw SQL or use other external querying tools.

LINQ enables data manipulation and retrieval using a syntax that is integrated with the language, providing a cleaner and more readable approach to querying and transforming data.

Key Features of LINQ:

  1. Unified Query Syntax: LINQ allows developers to query various data sources (like arrays, lists, XML, SQL databases) using a single syntax that integrates with the programming language.

  2. Strongly Typed Queries: Because LINQ queries are written in C# (or another .NET language), they are strongly typed and compile-time checked, reducing the risk of errors.

  3. IntelliSense Support: LINQ queries benefit from IntelliSense in Visual Studio, helping developers with auto-completion and real-time validation.

  4. Deferred Execution: LINQ queries are typically lazily evaluated. This means that the query is not executed until the data is actually accessed, which can improve performance in certain scenarios.

  5. In-memory and External Data Sources: LINQ can be used to query not just in-memory collections (e.g., arrays, lists) but also external data sources such as SQL databases or XML documents.

Types of LINQ:

  1. LINQ to Objects: Used for querying in-memory collections such as arrays, lists, dictionaries, etc.
  2. LINQ to SQL: Allows querying SQL databases through LINQ syntax, converting queries into SQL commands.
  3. LINQ to XML: Provides querying capabilities for XML documents.
  4. LINQ to Entities (Entity Framework): Allows querying of data stored in databases using the Entity Framework.
  5. LINQ to DataSets: Works with DataSet and DataTable objects in ADO.NET to perform queries on data stored in a DataSet.

Example of LINQ Syntax:

  1. LINQ Query Syntax: This is similar to SQL and is more declarative.

    var numbers = new List<int> { 1, 2, 3, 4, 5 };
    var query = from n in numbers
                where n % 2 == 0
                select n;
    
    foreach (var number in query)
    {
        Console.WriteLine(number);  // Output: 2, 4
    }
  2. LINQ Method Syntax: Uses method calls and lambda expressions and is often considered more flexible and concise.

    var numbers = new List<int> { 1, 2, 3, 4, 5 };
    var evenNumbers = numbers.Where(n => n % 2 == 0);
    
    foreach (var number in evenNumbers)
    {
        Console.WriteLine(number);  // Output: 2, 4
    }

Common LINQ Operators:

  • Where(): Filters a sequence based on a predicate.
  • Select(): Projects each element of a sequence into a new form.
  • OrderBy(): Sorts elements in ascending order.
  • OrderByDescending(): Sorts elements in descending order.
  • GroupBy(): Groups elements based on a key.
  • Join(): Joins two sequences based on a common key.
  • Distinct(): Removes duplicate elements from a sequence.
  • Aggregate(): Applies a function to a sequence to produce a single result.
  • FirstOrDefault(): Returns the first element in a sequence or a default value if the sequence is empty.

Example with LINQ to Objects:

using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    static void Main()
    {
        // Sample data
        var students = new List<Student>
        {
            new Student { Name = "John", Age = 21 },
            new Student { Name = "Jane", Age = 20 },
            new Student { Name = "Joe", Age = 22 }
        };

        // LINQ Query to select students older than 20
        var result = from student in students
                     where student.Age > 20
                     select student;

        foreach (var student in result)
        {
            Console.WriteLine(student.Name);  // Output: John, Joe
        }
    }
}

class Student
{
    public string Name { get; set; }
    public int Age { get; set; }
}

Benefits of LINQ:

  • Simplified Code: Reduces the amount of code required to query and manipulate data.
  • Readability: More intuitive and declarative, making the code easier to understand.
  • Reduced Error-Prone SQL: Instead of writing complex SQL strings, developers can write queries directly in C#.
  • Powerful Transformations: LINQ supports powerful transformations and combinations of data, like joining, grouping, and projecting.
  • Cross-Platform: LINQ can work with various data sources, from in-memory collections to remote databases.

Summary:

LINQ is a powerful feature in .NET that simplifies the way developers query and manipulate data. By using LINQ, you can perform operations on various data sources, such as in-memory collections, XML, and relational databases, with a unified and strongly typed syntax. It promotes cleaner, more readable code and reduces the amount of boilerplate code, especially when working with collections and external data sources.

Question: What is the difference between an abstract class and an interface in .NET?

Answer:

In .NET, both abstract classes and interfaces are used to define the structure of classes, but they differ in several key ways. The choice between using an abstract class or an interface depends on the requirements of your application.

1. Definition and Purpose:

  • Abstract Class: An abstract class is a class that cannot be instantiated directly and is meant to be inherited by other classes. It can contain both abstract methods (methods without a body) and concrete methods (methods with a body). It allows for shared code implementation across derived classes.

  • Interface: An interface is a contract that defines a set of methods and properties that the implementing class must provide. It can only contain method signatures, properties, events, or indexers (but no implementation). A class can implement multiple interfaces, which is useful for supporting multiple behaviors.

2. Inheritance and Implementation:

  • Abstract Class: A class can inherit from only one abstract class (single inheritance). The abstract class can provide default behavior (implemented methods), which can be optionally overridden in derived classes.

  • Interface: A class or struct can implement multiple interfaces, allowing it to support multiple behaviors or capabilities. An interface does not provide any implementation, only method and property declarations.

3. Methods and Properties:

  • Abstract Class:

    • Can contain both abstract methods (without implementation) and concrete methods (with implementation).
    • Can have fields (variables), constructors, and destructors.
    • Can provide default behavior that can be shared across derived classes.
    public abstract class Animal
    {
        public abstract void MakeSound();  // Abstract method
        
        public void Eat()  // Concrete method
        {
            Console.WriteLine("Eating...");
        }
    }
  • Interface:

    • Can only contain method signatures (no implementation), properties, events, or indexers.
    • Cannot have fields, constructors, or destructors.
    • Cannot provide any default behavior; only a contract for the implementing classes to follow.
    public interface IAnimal
    {
        void MakeSound();  // Method signature
        void Eat();  // Method signature
    }

4. Access Modifiers:

  • Abstract Class: Members of an abstract class (fields, methods, properties) can have various access modifiers (public, private, protected, etc.).

  • Interface: All members of an interface are implicitly public, and cannot have access modifiers. All methods, properties, etc., must be public.

public interface IExample
{
    void DoSomething();  // Implicitly public
}

5. Default Method Implementations (C# 8.0 and above):

  • Abstract Class: Can have concrete method implementations from the start, meaning that derived classes can reuse this implementation without modification.

  • Interface (C# 8.0+): Interfaces can now provide default implementations for methods (called default interface methods), but this is limited and is generally not used as often as in abstract classes.

public interface IExample
{
    void DoSomething();  // Signature only

    // Default implementation (C# 8.0+)
    void DefaultImplementation() 
    {
        Console.WriteLine("Default implementation");
    }
}

6. Constructors:

  • Abstract Class: Can have constructors, which are called when an object of a derived class is created. This allows you to initialize state in the abstract class.

  • Interface: Cannot have constructors. They define only the contract (methods, properties) that classes must implement.

7. Use Cases:

  • Abstract Class: Use an abstract class when:
    • You want to share code among multiple related classes (base functionality).
    • You want to provide default behavior (implemented methods).
    • You are working with a common base class and only need to inherit from one class.
  • Interface: Use an interface when:
    • You need to define a contract that multiple classes can implement (especially if those classes are unrelated).
    • You want to allow multiple inheritance (because a class can implement multiple interfaces).
    • You are defining a set of behaviors or capabilities that can be implemented by various types (e.g., IDisposable, IComparable).

8. Example: Abstract Class vs Interface:

Abstract Class Example:

public abstract class Animal
{
    public abstract void MakeSound();  // Abstract method

    public void Eat()
    {
        Console.WriteLine("Eating...");  // Concrete method
    }
}

public class Dog : Animal
{
    public override void MakeSound()
    {
        Console.WriteLine("Woof!");  // Override abstract method
    }
}

Interface Example:

public interface IAnimal
{
    void MakeSound();  // Method signature
    void Eat();  // Method signature
}

public class Dog : IAnimal
{
    public void MakeSound()
    {
        Console.WriteLine("Woof!");
    }

    public void Eat()
    {
        Console.WriteLine("Eating...");
    }
}

Summary of Key Differences:

FeatureAbstract ClassInterface
InheritanceSingle inheritance (a class can inherit from only one abstract class).Multiple inheritance (a class can implement multiple interfaces).
Method ImplementationCan have both abstract methods (without implementation) and concrete methods (with implementation).Can only have method signatures (no implementation, except default methods in C# 8.0+).
Access ModifiersCan have various access modifiers for members (public, private, protected).All members are implicitly public; no access modifiers allowed.
ConstructorsCan have constructors.Cannot have constructors.
Default ImplementationCan provide default behavior for methods.Can provide default implementation (from C# 8.0+).
Fields and PropertiesCan have fields, properties, and methods.Can have only method signatures, properties, events, and indexers.
Use CaseSuitable for defining common behavior and shared functionality.Suitable for defining contracts or capabilities that can be implemented by unrelated classes.

Conclusion:

  • Use an abstract class when you have a base class with some shared implementation that other derived classes can reuse and extend.
  • Use an interface when you want to define a contract that multiple unrelated classes can implement, especially if those classes need to support multiple behaviors or capabilities.

Read More

If you can’t get enough from this article, Aihirely has plenty more related information, such as .NET interview questions, .NET interview experiences, and details about various .NET job positions. Click here to check it out.

Related Posts

Trace Job opportunities

Hirely, your exclusive interview companion, empowers your competence and facilitates your interviews.

Get Started Now