C%23 Interview Questions and Answers

author image Hirely
at 06 Jan, 2025

Question: What is serialization in C#?

Answer:

Serialization in C# is the process of converting an object into a format that can be easily stored or transmitted, typically into a byte stream. This allows the object to be persisted to storage (like a file or database) or sent over a network to another system. Later, this serialized object can be deserialized, which means converting the byte stream back into an object.

Serialization is widely used for scenarios like:

  • Saving an object’s state to a file or database.
  • Sending objects over a network (e.g., through web services or APIs).
  • Storing objects in a format like JSON, XML, or binary.

Types of Serialization in C#:

  1. Binary Serialization:

    • Converts an object to a binary format.
    • The object is converted into a series of bytes, making it suitable for storage or transmission over a network in a compact, efficient form.
    • Binary serialization can preserve the full fidelity of objects, including private fields, but is less human-readable.

    Example of binary serialization:

    using System;
    using System.IO;
    using System.Runtime.Serialization.Formatters.Binary;
    
    [Serializable]
    public class Person
    {
        public string Name;
        public int Age;
    }
    
    class Program
    {
        static void Main()
        {
            Person person = new Person { Name = "Alice", Age = 30 };
            
            // Serialize the object to a file
            using (FileStream fs = new FileStream("person.dat", FileMode.Create))
            {
                BinaryFormatter formatter = new BinaryFormatter();
                formatter.Serialize(fs, person);
            }
        }
    }

    In the example above, the Person object is serialized to a binary file person.dat.

  2. XML Serialization:

    • Converts an object to an XML format (which is human-readable).
    • XML serialization only serializes public properties and fields, making it less flexible than binary serialization in terms of capturing the full state of an object.

    Example of XML serialization:

    using System;
    using System.IO;
    using System.Xml.Serialization;
    
    public class Person
    {
        public string Name;
        public int Age;
    }
    
    class Program
    {
        static void Main()
        {
            Person person = new Person { Name = "Bob", Age = 25 };
            
            // Serialize the object to an XML string
            XmlSerializer serializer = new XmlSerializer(typeof(Person));
            using (StringWriter writer = new StringWriter())
            {
                serializer.Serialize(writer, person);
                string xml = writer.ToString();
                Console.WriteLine(xml);
            }
        }
    }

    Output:

    <?xml version="1.0" encoding="utf-16"?>
    <Person xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
      <Name>Bob</Name>
      <Age>25</Age>
    </Person>
  3. JSON Serialization:

    • Converts an object to JSON format (JavaScript Object Notation), a widely used, lightweight data-interchange format.
    • JSON serialization is human-readable and is often used in web services and APIs.
    • In C#, the most common library for JSON serialization is Newtonsoft.Json (Json.NET), though .NET Core and later versions also include System.Text.Json for this purpose.

    Example of JSON serialization using System.Text.Json:

    using System;
    using System.Text.Json;
    
    public class Person
    {
        public string Name { get; set; }
        public int Age { get; set; }
    }
    
    class Program
    {
        static void Main()
        {
            Person person = new Person { Name = "Charlie", Age = 40 };
            
            // Serialize the object to JSON
            string jsonString = JsonSerializer.Serialize(person);
            Console.WriteLine(jsonString);
        }
    }

    Output:

    {"Name":"Charlie","Age":40}

Key Points to Note About Serialization in C#:

  • [Serializable] Attribute:

    • The class must be marked with the [Serializable] attribute to allow it to be serialized.
    • This attribute is necessary for binary serialization.

    Example:

    [Serializable]
    public class Person
    {
        public string Name;
        public int Age;
    }
  • Default Behavior:

    • In binary serialization, private fields can be serialized.
    • In XML and JSON serialization, only public properties and fields are serialized by default. However, you can control the serialization of private members using specific attributes (e.g., [XmlIgnore], [JsonIgnore]).
  • Custom Serialization:

    • C# allows custom serialization. By implementing the ISerializable interface, you can control how an object is serialized and deserialized, providing fine-grained control over the process.

Example of Custom Serialization:

using System;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;

[Serializable]
public class Person : ISerializable
{
    public string Name;
    public int Age;

    public Person(string name, int age)
    {
        Name = name;
        Age = age;
    }

    // Custom serialization constructor
    public Person(SerializationInfo info, StreamingContext context)
    {
        Name = info.GetString("Name");
        Age = info.GetInt32("Age");
    }

    // Custom serialization method
    public void GetObjectData(SerializationInfo info, StreamingContext context)
    {
        info.AddValue("Name", Name);
        info.AddValue("Age", Age);
    }
}

class Program
{
    static void Main()
    {
        Person person = new Person("Alice", 30);
        
        // Serialize the object to a file
        using (FileStream fs = new FileStream("person.dat", FileMode.Create))
        {
            IFormatter formatter = new BinaryFormatter();
            formatter.Serialize(fs, person);
        }
    }
}

In this example, the Person class implements the ISerializable interface, allowing custom logic for serialization and deserialization.


Summary:

  • Serialization is the process of converting an object to a format that can be easily stored or transmitted, such as binary, XML, or JSON.
  • C# provides several ways to serialize objects, including binary, XML, and JSON serialization.
  • The [Serializable] attribute marks classes for binary serialization, while XML and JSON serialization can be controlled using libraries like XmlSerializer and JsonSerializer.
  • Custom serialization can be achieved by implementing the ISerializable interface for more advanced scenarios.

Question: What are extension methods in C#?

Answer:

Extension methods in C# are a powerful feature that allows you to “add” new functionality to existing types without modifying their source code. Essentially, they enable you to extend the behavior of a class, interface, or delegate by adding methods to it. These methods appear as though they are part of the existing type, but they are defined outside the type itself.

Key Characteristics of Extension Methods:

  1. Defined in Static Classes:

    • Extension methods must be defined within a static class. The method itself must also be static.
  2. The First Parameter:

    • The first parameter of an extension method specifies the type that is being extended. This parameter must be preceded by the this keyword, which indicates that the method extends the functionality of the type specified by this parameter.
  3. Usage:

    • Once an extension method is defined, it can be called just like a regular method on the extended type, even if the type doesn’t have that method defined.

Syntax:

public static class MyExtensions
{
    public static void MyMethod(this MyClass obj)
    {
        // Method implementation
    }
}

Example:

Suppose you want to add a method ToUpperCase to the string class that converts a string to uppercase (even though string already has a built-in ToUpper() method, this is just for demonstration).

  1. Creating the Extension Method:

    using System;
    
    public static class StringExtensions
    {
        // Extension method to convert a string to uppercase
        public static string ToUpperCase(this string str)
        {
            return str.ToUpper();
        }
    }
  2. Using the Extension Method:

    class Program
    {
        static void Main()
        {
            string myString = "hello world";
            
            // Using the extension method
            string upperString = myString.ToUpperCase();
            
            Console.WriteLine(upperString);  // Output: HELLO WORLD
        }
    }

    In the example above:

    • The ToUpperCase method extends the functionality of the string class.
    • Although string already has a ToUpper() method, this demonstrates the syntax for creating and using an extension method.

Extension Methods for Interfaces:

You can also extend interfaces using extension methods. This is particularly useful when you want to add functionality to an interface that you cannot modify directly.

Example:

public interface IPrintable
{
    void Print();
}

public static class PrintableExtensions
{
    public static void PrintUpperCase(this IPrintable printable)
    {
        string printText = "hello, world!";
        Console.WriteLine(printText.ToUpper());
    }
}

class Program
{
    static void Main()
    {
        IPrintable printable = new PrintableClass();
        printable.PrintUpperCase();  // Using the extension method
    }
}

In the above example, the PrintUpperCase method is an extension method for any type that implements IPrintable, even though IPrintable doesn’t define that method itself.


When to Use Extension Methods:

  1. Adding Methods to Existing Types:

    • When you can’t modify the original source code, such as when you’re working with third-party libraries or built-in types.
  2. Improving Readability:

    • Extension methods can make code more readable by adding meaningful methods to existing types.
  3. Encapsulation:

    • You can encapsulate logic for specific tasks (like formatting, validation, or manipulation) that logically belong to a type but are not part of the type’s original implementation.
  4. LINQ and Collections:

    • Extension methods are heavily used in LINQ (Language Integrated Query). Many LINQ methods like Where(), Select(), and OrderBy() are all implemented as extension methods on IEnumerable<T>.

Limitations and Considerations:

  1. Readability:

    • Overusing extension methods can lead to confusion, as methods may appear to belong to a type, but they are defined externally.
  2. Namespace Pollution:

    • Since extension methods are statically imported, they can cause namespace conflicts if there are methods with the same name.
  3. Type Safety:

    • Extension methods can’t access private members of the type they are extending, and they cannot override methods or properties.
  4. Overriding Built-in Methods:

    • Extension methods cannot override existing methods. They simply provide additional functionality, but the compiler will prioritize the original method if both methods have the same name.

Summary:

  • Extension methods are a way to add methods to existing types in C# without modifying their source code.
  • They are defined in static classes, and the first parameter of the method is preceded by the this keyword, indicating the type being extended.
  • Extension methods allow for better code readability and encapsulation of reusable logic.
  • They are frequently used in LINQ and can be applied to both classes and interfaces.

Read More

If you can’t get enough from this article, Aihirely has plenty more related information, such as C# interview questions, C# interview experiences, and details about various C# 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