Attributes in C#
What is Attribute?
Attribute is a class used to give additional declarative information for the class, method, property, indexer, etc. By using attribute you can identify the behavior of the class, method, property, indexer, etc.
Following are the different types of attributes in C#:
It is used to specify whether the class or method is deprecated or not. Obsolete attribute contains two arguments:
If value is false, when deprecated method is used in the program then with warning the program will execute. If value is True, when deprecated method is used in application then compilation error will be displayed.
Example of Obsolete:
It is used to specify whether the method should be called or not. The conditional method must be a method in a class or structure declaration. A compile-time error occurs if the Conditional attribute is specified on a method in an interface declaration. The conditional method must have a return type of void. Conditional attribute is in System.Diagnostics namespace.
Example of Conditional:
This attribute will be used in xml web services in ASP.Net. In xml web service if any method or function is having this attribute then the method can be exposed on web or the method will execute in any browser.
Example of WebMethod:
DLL files are of two types: Managed dll and unmanaged dll. Old languages (such as Visual Basic 6.0, VC++, etc) and O.S. dll files are called unmanaged dll files. These will contain unmanaged code which will execute without CLR. Dot Net dll files are called managed dll files. It contains managed code which will execute through CLR. To use unmanaged dll files in managed code, DllImport attribute is used.
Example of DllImport:
5. Creating user defined Attributes:
User defined attribute can be used to give information about the class or method. i.e whether the class is user defined class or abstract class, base class etc. and for method you can specify whether it is user defined method, abstract method, virtual method, etc. Attribute class in System namespace is a base class for custom attribute or user defined attribute.
Example of Creating user defined Attributes:
In this way, we learned attributes in C# and some basic programs which will help beginners to understand attributes.
You may also be interested in...
- Slack Integration with C#
- Xamarin Forms: Getting Started
- Part 1: Introduction to C#
- Part 2: Arrays and Function in C#
- Part 3: OOPs Concepts in C#
- Part 4: Constructor/Destructor in C#
- Part 5: Abstract class in C#
- Part 6: Indexer,Delegates, Anonymous Method, Lambda expression in C#
- Part 7: Collections in C#
- Part 8: Generics in C#
- Part 9: Attributes in C#
- Part 10: Sealed/Partial class in C#
- Part 11: MultiThreading in C#