0
0
C Sharp (C#)programming~5 mins

Custom attribute classes in C Sharp (C#) - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Custom attribute classes
O(n)
Understanding Time Complexity

When we use custom attribute classes in C#, it's important to understand how the program's work grows as we apply these attributes to many parts of the code.

We want to know how the time to check or use these attributes changes when the number of classes or methods with attributes increases.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class MyCustomAttribute : Attribute
{
    public string Info { get; }
    public MyCustomAttribute(string info) => Info = info;
}

public class Example
{
    [MyCustomAttribute("Test")]
    public void Method() { }
}

// Later, reflection is used to find attributes:
var methods = typeof(Example).GetMethods();
foreach (var method in methods)
{
    var attrs = method.GetCustomAttributes(typeof(MyCustomAttribute), false);
    // process attrs
}
    

This code defines a custom attribute and then uses reflection to find all methods with that attribute.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Looping through all methods of a class to check for custom attributes.
  • How many times: Once for each method in the class.
How Execution Grows With Input

As the number of methods increases, the program checks each method one by one for the attribute.

Input Size (n)Approx. Operations
10About 10 attribute checks
100About 100 attribute checks
1000About 1000 attribute checks

Pattern observation: The work grows directly with the number of methods; doubling methods doubles the checks.

Final Time Complexity

Time Complexity: O(n)

This means the time to find attributes grows in a straight line with the number of methods checked.

Common Mistake

[X] Wrong: "Checking attributes is instant and does not depend on how many methods exist."

[OK] Correct: Each method must be checked one by one, so more methods mean more work.

Interview Connect

Understanding how attribute checks scale helps you write efficient code and reason about reflection performance in real projects.

Self-Check

What if we cached the attributes after the first check? How would the time complexity change when accessing attributes multiple times?