← Back to Articles         
C# – Reflection, Attributes & Serialization

C# – Reflection, Attributes & Serialization

Published on 12 Oct 2026     6 min read C#
Reflection

C# – Reflection, Attributes & Serialization

1. What is Reflection in C#, and when is it used?

Reflection is a feature in C# that allows us to inspect types, properties, methods, constructors, and attributes at runtime.

Reflection is available through the System.Reflection namespace.

Example

using System;

public class Employee
{
    public int Id { get; set; }
    public string Name { get; set; } = "";

    public void Display()
    {
        Console.WriteLine("Employee Details");
    }
}

class Program
{
    static void Main()
    {
        Type type = typeof(Employee);

        Console.WriteLine(type.Name);

        foreach (var property in type.GetProperties())
        {
            Console.WriteLine(property.Name);
        }

        foreach (var method in type.GetMethods(
            System.Reflection.BindingFlags.Public |
            System.Reflection.BindingFlags.Instance |
            System.Reflection.BindingFlags.DeclaredOnly))
        {
            Console.WriteLine(method.Name);
        }
    }
}

Output:

Employee
Id
Name
Display

Explanation

  • typeof(Employee) retrieves the type metadata.

  • GetProperties() retrieves public properties.

  • GetMethods() retrieves methods.

  • BindingFlags.DeclaredOnly excludes inherited methods.

When is Reflection used?

  • Dependency Injection containers.

  • Reading custom attributes.

  • Object mapping and serialization.

  • Plugin loading.

  • Unit testing frameworks.

Key Points

  • Reflection allows runtime inspection of types.

  • It can also dynamically create objects and invoke methods.

  • Reflection generally has more overhead than direct method calls.

  • Use reflection when runtime flexibility is required.

 

2. What are Attributes in C#?

Attributes are metadata added to classes, methods, properties, or parameters to provide additional information or control framework behavior.

Attributes are written using square brackets [ ].

Example

public class Employee
{
    [Required]
    public string Name { get; set; } = "";

    [Range(18, 60)]
    public int Age { get; set; }
}

Add:

using System.ComponentModel.DataAnnotations;

Explanation

  • [Required] indicates that Name must contain a value.

  • [Range(18, 60)] specifies the allowed age range.

  • Validation frameworks can read these attributes and enforce the rules.

Note: Attributes alone do not automatically execute validation. A validation framework or explicit validation call is required.

Common Attributes

Attribute

Purpose

[Required]

Field is required

[Range]

Validates numeric range

[Obsolete]

Marks code as outdated

[Serializable]

Marks a type for serializers that recognize it

[Authorize]

Restricts access in ASP.NET Core

[HttpGet]

Maps an HTTP GET endpoint

Key Points

  • Attributes provide metadata.

  • They can be applied to classes, methods, and properties.

  • Frameworks commonly inspect attributes using reflection.

  • Attributes can be built-in or custom.

 

3. How do you create Custom Attributes in C#?

A custom attribute is a user-defined attribute created by inheriting from the System.Attribute class.

Example

using System;

[AttributeUsage(AttributeTargets.Class)]
public class DeveloperAttribute : Attribute
{
    public string Name { get; }

    public DeveloperAttribute(string name)
    {
        Name = name;
    }
}

[Developer("Syed")]
public class EmployeeService
{
}

class Program
{
    static void Main()
    {
        Type type = typeof(EmployeeService);

        var attribute =
            Attribute.GetCustomAttribute(
                type,
                typeof(DeveloperAttribute))
            as DeveloperAttribute;

        Console.WriteLine(attribute?.Name);
    }
}

Output:

Syed

Explanation

  1. DeveloperAttribute inherits from Attribute.

  2. AttributeUsage restricts the attribute to classes.

  3. [Developer("Syed")] attaches metadata to EmployeeService.

  4. GetCustomAttribute() retrieves that metadata using reflection.

Flow

Custom Attribute
      |
      v
Apply to Class
      |
      v
Read using Reflection
      |
      v
Access Attribute Values

Key Points

  • Custom attributes inherit from System.Attribute.

  • AttributeUsage controls where attributes can be applied.

  • Reflection can retrieve attribute values at runtime.

  • Commonly used in validation, authorization, logging, and framework development.

 

4. What is Serialization and Deserialization?

Serialization converts an object into a format such as JSON or XML.

Deserialization converts serialized data back into an object.

Example

using System;
using System.Text.Json;

public class Employee
{
    public int Id { get; set; }
    public string Name { get; set; } = "";
}

class Program
{
    static void Main()
    {
        Employee emp = new Employee
        {
            Id = 101,
            Name = "Syed"
        };

        // Serialization
        string json = JsonSerializer.Serialize(emp);

        Console.WriteLine(json);

        // Deserialization
        Employee? result =
            JsonSerializer.Deserialize<Employee>(json);

        Console.WriteLine(result?.Name);
    }
}

Output:

{"Id":101,"Name":"Syed"}
Syed

Explanation

Serialization:

C# Object
    |
    | JsonSerializer.Serialize()
    v
JSON String

Deserialization:

JSON String
    |
    | JsonSerializer.Deserialize<T>()
    v
C# Object

Real-time example in ASP.NET Core Web API

When an API returns an employee:

[HttpGet]
public IActionResult GetEmployee()
{
    var employee = new Employee
    {
        Id = 101,
        Name = "Syed"
    };

    return Ok(employee);
}

ASP.NET Core normally serializes the returned employee object into JSON automatically.

Key Points

  • Serialization: Object → JSON.

  • Deserialization: JSON → Object.

  • Commonly used in Web APIs, caching, messaging, and file storage.

  • System.Text.Json is the default JSON serializer in modern ASP.NET Core.

 

5. What is the difference between System.Text.Json and Newtonsoft.Json?

Both libraries are used for JSON serialization and deserialization in .NET applications.

Comparison

Feature

System.Text.Json

Newtonsoft.Json

Provider

Microsoft

Newtonsoft

Package

Built into modern .NET

Separate NuGet package

Performance

Generally faster for common scenarios

Often slower for common scenarios

Memory allocation

Generally lower

Generally higher

JSON serialization

Supported

Supported

Custom converters

Supported

Supported

LINQ to JSON

JsonNode / JsonDocument

JObject / JToken

Advanced JSON features

Many supported

Mature, extensive support

ASP.NET Core default

Yes

No

Recommended for new projects

Generally preferred

When specific features are needed

Example

Using System.Text.Json

using System.Text.Json;

var employee = new
{
    Id = 101,
    Name = "Syed"
};

string json = JsonSerializer.Serialize(employee);

Using Newtonsoft.Json

using Newtonsoft.Json;

var employee = new
{
    Id = 101,
    Name = "Syed"
};

string json = JsonConvert.SerializeObject(employee);

Both produce:

{
  "Id": 101,
  "Name": "Syed"
}

(The actual output is compact JSON without indentation.)

When should we use each?

Use System.Text.Json when:

  • Developing new ASP.NET Core Web APIs.

  • Performance and low memory allocation are priorities.

  • Standard JSON serialization is sufficient.

  • Using Native AOT or source-generated serialization.

Use Newtonsoft.Json when:

  • Maintaining applications already using Newtonsoft.Json.

  • Using existing custom JsonConverter implementations.

  • Requiring Newtonsoft-specific JSON features.

  • Working with libraries that depend on Newtonsoft.Json.

Key Points

  • Both support serialization and deserialization.

  • System.Text.Json is generally preferred for new .NET applications.

  • Newtonsoft.Json provides a mature and flexible JSON API.

  • Switching between them may require changes to converters, attributes, and serializer settings.

 

Quick Interview Revision

Question

Important Answer

Reflection

Inspect and interact with type metadata at runtime

Attributes

Add metadata to code elements

Custom Attributes

Create metadata by inheriting from Attribute

Serialization

Convert an object into JSON/XML

Deserialization

Convert JSON/XML into an object

System.Text.Json vs Newtonsoft.Json

Built-in, generally faster serializer vs mature, feature-rich library

Important interview connection: Reflection and attributes often work together. For example, ASP.NET Core examines controller attributes such as [HttpGet] and [Authorize] to configure routing and authorization behavior.

← Back to Articles