SlideShare a Scribd company logo
1 of 18
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

What's hot (19)

Unit ii
Unit   iiUnit   ii
Unit ii
 
Linq
LinqLinq
Linq
 
Objects and classes in Visual Basic
Objects and classes in Visual BasicObjects and classes in Visual Basic
Objects and classes in Visual Basic
 
Constructor in java
Constructor in javaConstructor in java
Constructor in java
 
C# Generics
C# GenericsC# Generics
C# Generics
 
Chapter 8 - Exceptions and Assertions Edit summary
Chapter 8 - Exceptions and Assertions  Edit summaryChapter 8 - Exceptions and Assertions  Edit summary
Chapter 8 - Exceptions and Assertions Edit summary
 
Reflection in C Sharp
Reflection in C SharpReflection in C Sharp
Reflection in C Sharp
 
Reflection power pointpresentation ppt
Reflection power pointpresentation pptReflection power pointpresentation ppt
Reflection power pointpresentation ppt
 
Evolution of C# delegates
Evolution of C# delegatesEvolution of C# delegates
Evolution of C# delegates
 
Generics collections
Generics collectionsGenerics collections
Generics collections
 
Serialization in .NET
Serialization in .NETSerialization in .NET
Serialization in .NET
 
04. constructor & destructor
04. constructor & destructor04. constructor & destructor
04. constructor & destructor
 
C# Delegates
C# DelegatesC# Delegates
C# Delegates
 
Introduction to C++
Introduction to C++Introduction to C++
Introduction to C++
 
.NET Reflection
.NET Reflection.NET Reflection
.NET Reflection
 
Delegates and events
Delegates and events   Delegates and events
Delegates and events
 
Create and analyse programs
Create and analyse programsCreate and analyse programs
Create and analyse programs
 
Serialization/deserialization
Serialization/deserializationSerialization/deserialization
Serialization/deserialization
 
Explain Delegates step by step.
Explain Delegates step by step.Explain Delegates step by step.
Explain Delegates step by step.
 

Similar to Guide to Attributes in .NET - Everything You Need to Know

Reflecting On The Code Dom
Reflecting On The Code DomReflecting On The Code Dom
Reflecting On The Code DomNick Harrison
 
Attributes & .NET components
Attributes & .NET componentsAttributes & .NET components
Attributes & .NET componentsBình Trọng Án
 
Object-oriented programming
Object-oriented programmingObject-oriented programming
Object-oriented programmingNeelesh Shukla
 
Distributed System by Pratik Tambekar
Distributed System by Pratik TambekarDistributed System by Pratik Tambekar
Distributed System by Pratik TambekarPratik Tambekar
 
03 oo with-c-sharp
03 oo with-c-sharp03 oo with-c-sharp
03 oo with-c-sharpNaved khan
 
Learn about dot net attributes
Learn about dot net attributesLearn about dot net attributes
Learn about dot net attributessonia merchant
 
Understanding Reflection
Understanding ReflectionUnderstanding Reflection
Understanding ReflectionTamir Khason
 
13 iec t1_s1_oo_ps_session_19
13 iec t1_s1_oo_ps_session_1913 iec t1_s1_oo_ps_session_19
13 iec t1_s1_oo_ps_session_19Niit Care
 
Validate your entities with symfony validator and entity validation api
Validate your entities with symfony validator and entity validation apiValidate your entities with symfony validator and entity validation api
Validate your entities with symfony validator and entity validation apiRaffaele Chiocca
 
Policy Injection in ASP.NET using Enterprise Library 3.0
Policy Injection in ASP.NET using Enterprise Library 3.0Policy Injection in ASP.NET using Enterprise Library 3.0
Policy Injection in ASP.NET using Enterprise Library 3.0PhilWinstanley
 
.NET Attributes and Reflection - What a Developer Needs to Know...
.NET Attributes and Reflection - What a Developer Needs to Know....NET Attributes and Reflection - What a Developer Needs to Know...
.NET Attributes and Reflection - What a Developer Needs to Know...Dan Douglas
 
UnderstandingLDAP.ppt
UnderstandingLDAP.pptUnderstandingLDAP.ppt
UnderstandingLDAP.pptEfrizal Zaida
 

Similar to Guide to Attributes in .NET - Everything You Need to Know (20)

Reflection
ReflectionReflection
Reflection
 
Reflecting On The Code Dom
Reflecting On The Code DomReflecting On The Code Dom
Reflecting On The Code Dom
 
Reflection in C#
Reflection in C#Reflection in C#
Reflection in C#
 
201005 accelerometer and core Location
201005 accelerometer and core Location201005 accelerometer and core Location
201005 accelerometer and core Location
 
Attributes & .NET components
Attributes & .NET componentsAttributes & .NET components
Attributes & .NET components
 
Object-oriented programming
Object-oriented programmingObject-oriented programming
Object-oriented programming
 
Wpf from David Kossoglyad
Wpf from David KossoglyadWpf from David Kossoglyad
Wpf from David Kossoglyad
 
Generic
GenericGeneric
Generic
 
Distributed System by Pratik Tambekar
Distributed System by Pratik TambekarDistributed System by Pratik Tambekar
Distributed System by Pratik Tambekar
 
1204csharp
1204csharp1204csharp
1204csharp
 
03 oo with-c-sharp
03 oo with-c-sharp03 oo with-c-sharp
03 oo with-c-sharp
 
Learn about dot net attributes
Learn about dot net attributesLearn about dot net attributes
Learn about dot net attributes
 
Understanding Reflection
Understanding ReflectionUnderstanding Reflection
Understanding Reflection
 
13 iec t1_s1_oo_ps_session_19
13 iec t1_s1_oo_ps_session_1913 iec t1_s1_oo_ps_session_19
13 iec t1_s1_oo_ps_session_19
 
Validate your entities with symfony validator and entity validation api
Validate your entities with symfony validator and entity validation apiValidate your entities with symfony validator and entity validation api
Validate your entities with symfony validator and entity validation api
 
Policy Injection in ASP.NET using Enterprise Library 3.0
Policy Injection in ASP.NET using Enterprise Library 3.0Policy Injection in ASP.NET using Enterprise Library 3.0
Policy Injection in ASP.NET using Enterprise Library 3.0
 
Actionscript
ActionscriptActionscript
Actionscript
 
.NET Attributes and Reflection - What a Developer Needs to Know...
.NET Attributes and Reflection - What a Developer Needs to Know....NET Attributes and Reflection - What a Developer Needs to Know...
.NET Attributes and Reflection - What a Developer Needs to Know...
 
Objects and Types C#
Objects and Types C#Objects and Types C#
Objects and Types C#
 
UnderstandingLDAP.ppt
UnderstandingLDAP.pptUnderstandingLDAP.ppt
UnderstandingLDAP.ppt
 

More from Prem Kumar Badri

Module 14 properties and indexers
Module 14 properties and indexersModule 14 properties and indexers
Module 14 properties and indexersPrem Kumar Badri
 
Module 10 : creating and destroying objects
Module 10 : creating and destroying objectsModule 10 : creating and destroying objects
Module 10 : creating and destroying objectsPrem Kumar Badri
 
Module 9 : using reference type variables
Module 9 : using reference type variablesModule 9 : using reference type variables
Module 9 : using reference type variablesPrem Kumar Badri
 
Module 8 : Implementing collections and generics
Module 8 : Implementing collections and genericsModule 8 : Implementing collections and generics
Module 8 : Implementing collections and genericsPrem Kumar Badri
 
Module 6 : Essentials of Object Oriented Programming
Module 6 : Essentials of Object Oriented ProgrammingModule 6 : Essentials of Object Oriented Programming
Module 6 : Essentials of Object Oriented ProgrammingPrem Kumar Badri
 
Module 5 : Statements & Exceptions
Module 5 : Statements & ExceptionsModule 5 : Statements & Exceptions
Module 5 : Statements & ExceptionsPrem Kumar Badri
 
Module 4 : methods & parameters
Module 4 : methods & parametersModule 4 : methods & parameters
Module 4 : methods & parametersPrem Kumar Badri
 
Module 3 : using value type variables
Module 3 : using value type variablesModule 3 : using value type variables
Module 3 : using value type variablesPrem Kumar Badri
 
Module 1 : Overview of the Microsoft .NET Platform
Module 1 : Overview of the Microsoft .NET PlatformModule 1 : Overview of the Microsoft .NET Platform
Module 1 : Overview of the Microsoft .NET PlatformPrem Kumar Badri
 
C# Non generics collection
C# Non generics collectionC# Non generics collection
C# Non generics collectionPrem Kumar Badri
 
C# Filtering in generic collections
C# Filtering in generic collectionsC# Filtering in generic collections
C# Filtering in generic collectionsPrem Kumar Badri
 

More from Prem Kumar Badri (20)

Module 14 properties and indexers
Module 14 properties and indexersModule 14 properties and indexers
Module 14 properties and indexers
 
Module 11 : Inheritance
Module 11 : InheritanceModule 11 : Inheritance
Module 11 : Inheritance
 
Module 10 : creating and destroying objects
Module 10 : creating and destroying objectsModule 10 : creating and destroying objects
Module 10 : creating and destroying objects
 
Module 9 : using reference type variables
Module 9 : using reference type variablesModule 9 : using reference type variables
Module 9 : using reference type variables
 
Module 8 : Implementing collections and generics
Module 8 : Implementing collections and genericsModule 8 : Implementing collections and generics
Module 8 : Implementing collections and generics
 
Module 7 : Arrays
Module 7 : ArraysModule 7 : Arrays
Module 7 : Arrays
 
Module 6 : Essentials of Object Oriented Programming
Module 6 : Essentials of Object Oriented ProgrammingModule 6 : Essentials of Object Oriented Programming
Module 6 : Essentials of Object Oriented Programming
 
Module 5 : Statements & Exceptions
Module 5 : Statements & ExceptionsModule 5 : Statements & Exceptions
Module 5 : Statements & Exceptions
 
Module 4 : methods & parameters
Module 4 : methods & parametersModule 4 : methods & parameters
Module 4 : methods & parameters
 
Module 3 : using value type variables
Module 3 : using value type variablesModule 3 : using value type variables
Module 3 : using value type variables
 
Module 2: Overview of c#
Module 2:  Overview of c#Module 2:  Overview of c#
Module 2: Overview of c#
 
Module 1 : Overview of the Microsoft .NET Platform
Module 1 : Overview of the Microsoft .NET PlatformModule 1 : Overview of the Microsoft .NET Platform
Module 1 : Overview of the Microsoft .NET Platform
 
C# Non generics collection
C# Non generics collectionC# Non generics collection
C# Non generics collection
 
C# Multi threading
C# Multi threadingC# Multi threading
C# Multi threading
 
C# Method overloading
C# Method overloadingC# Method overloading
C# Method overloading
 
C# Inheritance
C# InheritanceC# Inheritance
C# Inheritance
 
C# Generic collections
C# Generic collectionsC# Generic collections
C# Generic collections
 
C# Global Assembly Cache
C# Global Assembly CacheC# Global Assembly Cache
C# Global Assembly Cache
 
C# Filtering in generic collections
C# Filtering in generic collectionsC# Filtering in generic collections
C# Filtering in generic collections
 
C# File IO Operations
C# File IO OperationsC# File IO Operations
C# File IO Operations
 

Recently uploaded

Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceSamikshaHamane
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationnomboosow
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
Types of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxTypes of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxEyham Joco
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxmanuelaromero2013
 
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfFraming an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfUjwalaBharambe
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfSumit Tiwari
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxGaneshChakor2
 
Biting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdfBiting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdfadityarao40181
 
Capitol Tech U Doctoral Presentation - April 2024.pptx
Capitol Tech U Doctoral Presentation - April 2024.pptxCapitol Tech U Doctoral Presentation - April 2024.pptx
Capitol Tech U Doctoral Presentation - April 2024.pptxCapitolTechU
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon AUnboundStockton
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTiammrhaywood
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxRaymartEstabillo3
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxiammrhaywood
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxthorishapillay1
 

Recently uploaded (20)

Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in Pharmacovigilance
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communication
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 
OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...
 
Types of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxTypes of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptx
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptx
 
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfFraming an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptx
 
Biting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdfBiting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdf
 
Capitol Tech U Doctoral Presentation - April 2024.pptx
Capitol Tech U Doctoral Presentation - April 2024.pptxCapitol Tech U Doctoral Presentation - April 2024.pptx
Capitol Tech U Doctoral Presentation - April 2024.pptx
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon A
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptx
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
 

Guide to Attributes in .NET - Everything You Need to Know

  • 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