SlideShare a Scribd company logo
Attributes
Overview
 Overview of Attributes
 Defining Custom Attributes
 Retrieving Attribute Values
Overview of Attributes
 Introduction to Attributes
 Applying Attributes
 Common Predefined Attributes
 Using the Conditional Attribute
 Using the DllImport Attribute
 Using the Transaction Attribute
Introduction to Attributes
 Attributes are:
 Declarative tags that convey information to the runtime
 Stored with the metadata of the element
 .NET Framework provides predefined attributes
 The runtime contains code to examine values of attributes
and act on them
Applying Attributes
 Syntax: Use square brackets to specify an attribute
 To apply multiple attributes to an element, you can:
 Specify multiple attributes in separate square brackets
 Use a single square bracket and separate attributes with
commas
 For some elements such as assemblies, specify the element
name associated with the attribute explicitly
[attribute(positional_parameters,named_parameter=value, ...)]
element
Common Predefined Attributes
 .NET provides many predefined attributes
 General attributes
 COM interoperability attributes
 Transaction handling attributes
 Visual designer component building attributes
Using the Conditional Attribute
 Serves as a debugging tool
 Causes conditional compilation of method calls,
depending on the value of a programmer-defined symbol
 Does not cause conditional compilation of the method
itself
 Restrictions on methods
 Must have return type of void
 Must not be declared as override
 Must not be from an inherited interface
using System.Diagnostics;
...
class MyClass
{
[Conditional ("DEBUGGING")]
public static void MyMethod( )
{
...
}
}
Using the DllImport Attribute
 With the DllImport attribute, you can:
 Invoke unmanaged code in DLLs from a C# environment
 Tag an external method to show that it resides in an
unmanaged DLL
using System.Runtime.InteropServices;
...
public class MyClass( )
{
[DllImport("MyDLL.dll", EntryPoint="MyFunction")]
public static extern int MyFunction(string param1);
...
int result = MyFunction("Hello Unmanaged Code");
...
}
Using the Transaction Attribute
 To manage transactions in COM+
 Specify that your component be included when a
transaction commit is requested
 Use a Transaction attribute on the class that implements the
component
using System.EnterpriseServices;
...
[Transaction(TransactionOption.Required)]
public class MyTransactionalComponent
{
...
}
Defining Custom Attributes
 Defining Custom Attribute Scope
 Defining an Attribute Class
 Processing a Custom Attribute
 Using Multiple Attributes
Defining Custom Attribute Scope
 Use the AttributeUsage tag to define scope
 Example
 Use the bitwise “or” operator (|) to specify multiple
elements
 Example
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct)]
public class MyAttribute: System.Attribute
{ ... }
[AttributeUsage(AttributeTargets.Method)]
public class MyAttribute: System.Attribute
{ ... }
Defining an Attribute Class
 Deriving an attribute class
 All attribute classes must derive from System.Attribute,
directly or indirectly
 Suffix name of attribute class with “Attribute”
 Components of an attribute class
 Define a single constructor for each attribute class by using
a positional parameter
 Use properties to set an optional value by using a named
parameter
Processing a Custom Attribute
The Compilation Process
1. Searches for the attribute class
2. Checks the scope of the attribute
3. Checks for a constructor in the attribute
4. Creates an instance of the object
5. Checks for a named parameter
6. Sets field or property to named parameter value
7. Saves current state of attribute class
Using Multiple Attributes
 An element can have more than one attribute
 Define both attributes separately
 An element can have more than one instance of the
same attribute
 Use AllowMultiple = true
Retrieving Attribute Values
 Examining Class Metadata
 Querying for Attribute Information
Examining Class Metadata
 To query class metadata information:
 Use the MemberInfo class in System.Reflection
 Populate a MemberInfo object by using System.Type
 Create a System.Type object by using the typeof operator
 Example
System.Reflection.MemberInfo typeInfo;
typeInfo = typeof(MyClass);
Querying for Attribute Information
 To retrieve attribute information:
 Use GetCustomAttributes to retrieve all attribute
information as an array
 Iterate through the array and examine the values of each
element in the array
 Use the IsDefined method to determine whether a
particular attribute has been defined for a class
System.Reflection.MemberInfo typeInfo;
typeInfo = typeof(MyClass);
object[ ] attrs = typeInfo.GetCustomAttributes(false);
Review
 Overview of Attributes
 Defining Custom Attributes
 Retrieving Attribute Values

More Related Content

What's hot (19)

PPTX
Unit ii
donny101
 
PPT
Linq
Vishwa Mohan
 
PPTX
Objects and classes in Visual Basic
Sangeetha Sg
 
PPTX
Constructor in java
Pavith Gunasekara
 
PPTX
C# Generics
Rohit Vipin Mathews
 
PPT
Chapter 8 - Exceptions and Assertions Edit summary
Eduardo Bergavera
 
PPT
Reflection in C Sharp
Harman Bajwa
 
PPTX
Reflection power pointpresentation ppt
Rohit Vipin Mathews
 
PPTX
Evolution of C# delegates
mbaric
 
PPT
Generics collections
Yaswanth Babu Gummadivelli
 
DOC
Serialization in .NET
Abhi Arya
 
PDF
04. constructor & destructor
Haresh Jaiswal
 
PPTX
C# Delegates
Raghuveer Guthikonda
 
PDF
Introduction to C++
Pranali Chaudhari
 
PPT
.NET Reflection
Robert MacLean
 
PPTX
Delegates and events
Gayathri Ganesh
 
PPT
Create and analyse programs
Dr. C.V. Suresh Babu
 
PPT
Serialization/deserialization
Young Alista
 
PPTX
Explain Delegates step by step.
Questpond
 
Unit ii
donny101
 
Objects and classes in Visual Basic
Sangeetha Sg
 
Constructor in java
Pavith Gunasekara
 
C# Generics
Rohit Vipin Mathews
 
Chapter 8 - Exceptions and Assertions Edit summary
Eduardo Bergavera
 
Reflection in C Sharp
Harman Bajwa
 
Reflection power pointpresentation ppt
Rohit Vipin Mathews
 
Evolution of C# delegates
mbaric
 
Generics collections
Yaswanth Babu Gummadivelli
 
Serialization in .NET
Abhi Arya
 
04. constructor & destructor
Haresh Jaiswal
 
C# Delegates
Raghuveer Guthikonda
 
Introduction to C++
Pranali Chaudhari
 
.NET Reflection
Robert MacLean
 
Delegates and events
Gayathri Ganesh
 
Create and analyse programs
Dr. C.V. Suresh Babu
 
Serialization/deserialization
Young Alista
 
Explain Delegates step by step.
Questpond
 

Similar to Module 15 attributes (20)

PDF
Learn about dot net attributes
sonia merchant
 
PDF
CSharp Advanced L05-Attributes+Reflection
Mohammad Shaker
 
PPTX
Reflection in C#
Rohit Vipin Mathews
 
PPTX
Dotnet :Attributes
Maitree Patel
 
PPT
Attributes & .NET components
Bình Trọng Án
 
PPT
Learning .NET Attributes
Pooja Gaikwad
 
PPT
Learn dot net attributes
sonia merchant
 
KEY
Attributes, reflection, and dynamic programming
LearnNowOnline
 
PPS
13 iec t1_s1_oo_ps_session_19
Niit Care
 
PPT
Reflecting On The Code Dom
Nick Harrison
 
PPT
Generic
abhay singh
 
PPT
C#
Joni
 
PPTX
06.1 .Net memory management
Victor Matyushevskyy
 
DOC
Framework Project Portfolio
Domingos Salvador
 
PDF
1204csharp
g_hemanth17
 
PPT
NNUG Certification Presentation
Niall Merrigan
 
PPT
Framework Design Guidelines
Mohamed Meligy
 
PPTX
Effective c# part1
Yuriy Seniuk
 
PPT
Policy Injection in ASP.NET using Enterprise Library 3.0
PhilWinstanley
 
Learn about dot net attributes
sonia merchant
 
CSharp Advanced L05-Attributes+Reflection
Mohammad Shaker
 
Reflection in C#
Rohit Vipin Mathews
 
Dotnet :Attributes
Maitree Patel
 
Attributes & .NET components
Bình Trọng Án
 
Learning .NET Attributes
Pooja Gaikwad
 
Learn dot net attributes
sonia merchant
 
Attributes, reflection, and dynamic programming
LearnNowOnline
 
13 iec t1_s1_oo_ps_session_19
Niit Care
 
Reflecting On The Code Dom
Nick Harrison
 
Generic
abhay singh
 
C#
Joni
 
06.1 .Net memory management
Victor Matyushevskyy
 
Framework Project Portfolio
Domingos Salvador
 
1204csharp
g_hemanth17
 
NNUG Certification Presentation
Niall Merrigan
 
Framework Design Guidelines
Mohamed Meligy
 
Effective c# part1
Yuriy Seniuk
 
Policy Injection in ASP.NET using Enterprise Library 3.0
PhilWinstanley
 
Ad

More from Prem Kumar Badri (20)

PPTX
Module 14 properties and indexers
Prem Kumar Badri
 
PPTX
Module 11 : Inheritance
Prem Kumar Badri
 
PPTX
Module 10 : creating and destroying objects
Prem Kumar Badri
 
PPTX
Module 9 : using reference type variables
Prem Kumar Badri
 
PPTX
Module 8 : Implementing collections and generics
Prem Kumar Badri
 
PPTX
Module 7 : Arrays
Prem Kumar Badri
 
PPTX
Module 6 : Essentials of Object Oriented Programming
Prem Kumar Badri
 
PPTX
Module 5 : Statements & Exceptions
Prem Kumar Badri
 
PPTX
Module 4 : methods & parameters
Prem Kumar Badri
 
PPTX
Module 3 : using value type variables
Prem Kumar Badri
 
PPTX
Module 2: Overview of c#
Prem Kumar Badri
 
PPTX
Module 1 : Overview of the Microsoft .NET Platform
Prem Kumar Badri
 
PPTX
C# Non generics collection
Prem Kumar Badri
 
PPTX
C# Multi threading
Prem Kumar Badri
 
PPT
C# Method overloading
Prem Kumar Badri
 
PPTX
C# Inheritance
Prem Kumar Badri
 
PPTX
C# Generic collections
Prem Kumar Badri
 
PPTX
C# Global Assembly Cache
Prem Kumar Badri
 
PPTX
C# Filtering in generic collections
Prem Kumar Badri
 
PPTX
C# File IO Operations
Prem Kumar Badri
 
Module 14 properties and indexers
Prem Kumar Badri
 
Module 11 : Inheritance
Prem Kumar Badri
 
Module 10 : creating and destroying objects
Prem Kumar Badri
 
Module 9 : using reference type variables
Prem Kumar Badri
 
Module 8 : Implementing collections and generics
Prem Kumar Badri
 
Module 7 : Arrays
Prem Kumar Badri
 
Module 6 : Essentials of Object Oriented Programming
Prem Kumar Badri
 
Module 5 : Statements & Exceptions
Prem Kumar Badri
 
Module 4 : methods & parameters
Prem Kumar Badri
 
Module 3 : using value type variables
Prem Kumar Badri
 
Module 2: Overview of c#
Prem Kumar Badri
 
Module 1 : Overview of the Microsoft .NET Platform
Prem Kumar Badri
 
C# Non generics collection
Prem Kumar Badri
 
C# Multi threading
Prem Kumar Badri
 
C# Method overloading
Prem Kumar Badri
 
C# Inheritance
Prem Kumar Badri
 
C# Generic collections
Prem Kumar Badri
 
C# Global Assembly Cache
Prem Kumar Badri
 
C# Filtering in generic collections
Prem Kumar Badri
 
C# File IO Operations
Prem Kumar Badri
 
Ad

Recently uploaded (20)

PPTX
SPINA BIFIDA: NURSING MANAGEMENT .pptx
PRADEEP ABOTHU
 
PPTX
Quarter1-English3-W4-Identifying Elements of the Story
FLORRACHELSANTOS
 
PDF
SSHS-2025-PKLP_Quarter-1-Dr.-Kerby-Alvarez.pdf
AishahSangcopan1
 
PPTX
MENINGITIS: NURSING MANAGEMENT, BACTERIAL MENINGITIS, VIRAL MENINGITIS.pptx
PRADEEP ABOTHU
 
PPTX
2025 Winter SWAYAM NPTEL & A Student.pptx
Utsav Yagnik
 
PDF
community health nursing question paper 2.pdf
Prince kumar
 
PDF
ARAL_Orientation_Day-2-Sessions_ARAL-Readung ARAL-Mathematics ARAL-Sciencev2.pdf
JoelVilloso1
 
PPT
Talk on Critical Theory, Part II, Philosophy of Social Sciences
Soraj Hongladarom
 
PDF
IMP NAAC-Reforms-Stakeholder-Consultation-Presentation-on-Draft-Metrics-Unive...
BHARTIWADEKAR
 
PPTX
PATIENT ASSIGNMENTS AND NURSING CARE RESPONSIBILITIES.pptx
PRADEEP ABOTHU
 
PPTX
How to Set Maximum Difference Odoo 18 POS
Celine George
 
PPTX
STAFF DEVELOPMENT AND WELFARE: MANAGEMENT
PRADEEP ABOTHU
 
PDF
0725.WHITEPAPER-UNIQUEWAYSOFPROTOTYPINGANDUXNOW.pdf
Thomas GIRARD, MA, CDP
 
PPTX
Soil and agriculture microbiology .pptx
Keerthana Ramesh
 
PPTX
BANDHA (BANDAGES) PPT.pptx ayurveda shalya tantra
rakhan78619
 
PPTX
Views on Education of Indian Thinkers Mahatma Gandhi.pptx
ShrutiMahanta1
 
PPTX
Mathematics 5 - Time Measurement: Time Zone
menchreo
 
PDF
Isharyanti-2025-Cross Language Communication in Indonesian Language
Neny Isharyanti
 
PDF
ARAL-Orientation_Morning-Session_Day-11.pdf
JoelVilloso1
 
PPTX
A PPT on Alfred Lord Tennyson's Ulysses.
Beena E S
 
SPINA BIFIDA: NURSING MANAGEMENT .pptx
PRADEEP ABOTHU
 
Quarter1-English3-W4-Identifying Elements of the Story
FLORRACHELSANTOS
 
SSHS-2025-PKLP_Quarter-1-Dr.-Kerby-Alvarez.pdf
AishahSangcopan1
 
MENINGITIS: NURSING MANAGEMENT, BACTERIAL MENINGITIS, VIRAL MENINGITIS.pptx
PRADEEP ABOTHU
 
2025 Winter SWAYAM NPTEL & A Student.pptx
Utsav Yagnik
 
community health nursing question paper 2.pdf
Prince kumar
 
ARAL_Orientation_Day-2-Sessions_ARAL-Readung ARAL-Mathematics ARAL-Sciencev2.pdf
JoelVilloso1
 
Talk on Critical Theory, Part II, Philosophy of Social Sciences
Soraj Hongladarom
 
IMP NAAC-Reforms-Stakeholder-Consultation-Presentation-on-Draft-Metrics-Unive...
BHARTIWADEKAR
 
PATIENT ASSIGNMENTS AND NURSING CARE RESPONSIBILITIES.pptx
PRADEEP ABOTHU
 
How to Set Maximum Difference Odoo 18 POS
Celine George
 
STAFF DEVELOPMENT AND WELFARE: MANAGEMENT
PRADEEP ABOTHU
 
0725.WHITEPAPER-UNIQUEWAYSOFPROTOTYPINGANDUXNOW.pdf
Thomas GIRARD, MA, CDP
 
Soil and agriculture microbiology .pptx
Keerthana Ramesh
 
BANDHA (BANDAGES) PPT.pptx ayurveda shalya tantra
rakhan78619
 
Views on Education of Indian Thinkers Mahatma Gandhi.pptx
ShrutiMahanta1
 
Mathematics 5 - Time Measurement: Time Zone
menchreo
 
Isharyanti-2025-Cross Language Communication in Indonesian Language
Neny Isharyanti
 
ARAL-Orientation_Morning-Session_Day-11.pdf
JoelVilloso1
 
A PPT on Alfred Lord Tennyson's Ulysses.
Beena E S
 

Module 15 attributes

  • 2. Overview  Overview of Attributes  Defining Custom Attributes  Retrieving Attribute Values
  • 3. Overview of Attributes  Introduction to Attributes  Applying Attributes  Common Predefined Attributes  Using the Conditional Attribute  Using the DllImport Attribute  Using the Transaction Attribute
  • 4. Introduction to Attributes  Attributes are:  Declarative tags that convey information to the runtime  Stored with the metadata of the element  .NET Framework provides predefined attributes  The runtime contains code to examine values of attributes and act on them
  • 5. Applying Attributes  Syntax: Use square brackets to specify an attribute  To apply multiple attributes to an element, you can:  Specify multiple attributes in separate square brackets  Use a single square bracket and separate attributes with commas  For some elements such as assemblies, specify the element name associated with the attribute explicitly [attribute(positional_parameters,named_parameter=value, ...)] element
  • 6. Common Predefined Attributes  .NET provides many predefined attributes  General attributes  COM interoperability attributes  Transaction handling attributes  Visual designer component building attributes
  • 7. Using the Conditional Attribute  Serves as a debugging tool  Causes conditional compilation of method calls, depending on the value of a programmer-defined symbol  Does not cause conditional compilation of the method itself  Restrictions on methods  Must have return type of void  Must not be declared as override  Must not be from an inherited interface using System.Diagnostics; ... class MyClass { [Conditional ("DEBUGGING")] public static void MyMethod( ) { ... } }
  • 8. Using the DllImport Attribute  With the DllImport attribute, you can:  Invoke unmanaged code in DLLs from a C# environment  Tag an external method to show that it resides in an unmanaged DLL using System.Runtime.InteropServices; ... public class MyClass( ) { [DllImport("MyDLL.dll", EntryPoint="MyFunction")] public static extern int MyFunction(string param1); ... int result = MyFunction("Hello Unmanaged Code"); ... }
  • 9. Using the Transaction Attribute  To manage transactions in COM+  Specify that your component be included when a transaction commit is requested  Use a Transaction attribute on the class that implements the component using System.EnterpriseServices; ... [Transaction(TransactionOption.Required)] public class MyTransactionalComponent { ... }
  • 10. Defining Custom Attributes  Defining Custom Attribute Scope  Defining an Attribute Class  Processing a Custom Attribute  Using Multiple Attributes
  • 11. Defining Custom Attribute Scope  Use the AttributeUsage tag to define scope  Example  Use the bitwise “or” operator (|) to specify multiple elements  Example [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct)] public class MyAttribute: System.Attribute { ... } [AttributeUsage(AttributeTargets.Method)] public class MyAttribute: System.Attribute { ... }
  • 12. Defining an Attribute Class  Deriving an attribute class  All attribute classes must derive from System.Attribute, directly or indirectly  Suffix name of attribute class with “Attribute”  Components of an attribute class  Define a single constructor for each attribute class by using a positional parameter  Use properties to set an optional value by using a named parameter
  • 13. Processing a Custom Attribute The Compilation Process 1. Searches for the attribute class 2. Checks the scope of the attribute 3. Checks for a constructor in the attribute 4. Creates an instance of the object 5. Checks for a named parameter 6. Sets field or property to named parameter value 7. Saves current state of attribute class
  • 14. Using Multiple Attributes  An element can have more than one attribute  Define both attributes separately  An element can have more than one instance of the same attribute  Use AllowMultiple = true
  • 15. Retrieving Attribute Values  Examining Class Metadata  Querying for Attribute Information
  • 16. Examining Class Metadata  To query class metadata information:  Use the MemberInfo class in System.Reflection  Populate a MemberInfo object by using System.Type  Create a System.Type object by using the typeof operator  Example System.Reflection.MemberInfo typeInfo; typeInfo = typeof(MyClass);
  • 17. Querying for Attribute Information  To retrieve attribute information:  Use GetCustomAttributes to retrieve all attribute information as an array  Iterate through the array and examine the values of each element in the array  Use the IsDefined method to determine whether a particular attribute has been defined for a class System.Reflection.MemberInfo typeInfo; typeInfo = typeof(MyClass); object[ ] attrs = typeInfo.GetCustomAttributes(false);
  • 18. Review  Overview of Attributes  Defining Custom Attributes  Retrieving Attribute Values