Introduction
Attributes add extra information to your code. They help tools and the program understand how to use parts of your code.
Attributes add extra information to your code. They help tools and the program understand how to use parts of your code.
[AttributeName(parameters)] public class MyClass { // code here }
Person class as serializable.[Serializable] public class Person { public string Name; }
[Obsolete("Use NewMethod instead")] public void OldMethod() { // code }
[Description("This is a sample property")] public string SampleProperty { get; set; }
This program shows how to declare attributes on a class, property, and method. It runs two greeting methods, one marked obsolete.
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(); } }
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.
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.
Serializable above a class in C#?[] placed above the code element.Serializable must be enclosed in square brackets before the class declaration."Test" for Obsolete?[Obsolete("Use NewMethod instead")]
public void OldMethod() { Console.WriteLine("Old"); }
public void NewMethod() { Console.WriteLine("New"); }
OldMethod();Obsolete attribute marks a method as outdated but does not prevent it from running.OldMethod() will execute its body and print "Old" to the console.[Obsolete("Deprecated"]
public void Old() { }[Obsolete("Deprecated"] but the parentheses are not closed properly.) before the closing square bracket.Info that takes a string parameter description. Which is the correct way to declare it?Attribute and named with Attribute suffix.description to accept data when used.Pass the test and this pattern moves unknown