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

Attribute declaration syntax in C Sharp (C#)

Choose your learning style9 modes available
Introduction

Attributes add extra information to your code. They help tools and the program understand how to use parts of your code.

When you want to mark a class as serializable so it can be saved or sent over a network.
When you want to tell the compiler to ignore a warning for a specific method.
When you want to add a description to a property for documentation tools.
When you want to specify that a method should run before a test starts in testing frameworks.
Syntax
C Sharp (C#)
[AttributeName(parameters)]
public class MyClass {
    // code here
}
Attributes are placed in square brackets above the code element they describe.
You can add parameters inside the parentheses if the attribute needs extra information.
Examples
This marks the Person class as serializable.
C Sharp (C#)
[Serializable]
public class Person {
    public string Name;
}
This marks the method as obsolete and shows a message to use another method.
C Sharp (C#)
[Obsolete("Use NewMethod instead")]
public void OldMethod() {
    // code
}
This adds a description to a property, useful for documentation.
C Sharp (C#)
[Description("This is a sample property")]
public string SampleProperty { get; set; }
Sample Program

This program shows how to declare attributes on a class, property, and method. It runs two greeting methods, one marked obsolete.

C Sharp (C#)
using System;
using System.ComponentModel;

[Serializable]
public class Person {
    [Description("Person's full name")]
    public string Name { get; set; }

    [Obsolete("Use NewGreet instead")]
    public void OldGreet() {
        Console.WriteLine("Hello from old greet!");
    }

    public void NewGreet() {
        Console.WriteLine($"Hello, {Name}!");
    }
}

class Program {
    static void Main() {
        Person p = new Person { Name = "Alice" };
        p.NewGreet();
        p.OldGreet();
    }
}
OutputSuccess
Important Notes

Attributes do not change how your code runs by themselves; they provide extra info for tools or runtime.

You can create your own custom attributes by inheriting from System.Attribute.

Summary

Attributes add extra information to code elements using square brackets.

They can have parameters to provide more details.

Common uses include marking classes, methods, or properties for special treatment.