/
Programming in C# 	 Attributes Programming in C# 	 Attributes

Programming in C# Attributes - PowerPoint Presentation

quinn
quinn . @quinn
Follow
66 views
Uploaded On 2023-09-21

Programming in C# Attributes - PPT Presentation

CSE 494R proposed course for 459 Programming in C Prof Roger Crawfis Attributes Many systems have a need to decorate code with additional information Traditional solutions Add keywords or ID: 1018970

attribute class helpurlattribute attributes class attribute attributes helpurlattribute type assembly custom debug string public system metadata programming preprocessor conditional

Share:

Link:

Embed:

Download Presentation from below link

Download Presentation The PPT/PDF document "Programming in C# Attributes" is the property of its rightful owner. Permission is granted to download and print the materials on this web site for personal, non-commercial use only, and to display it on your personal computer provided you do not modify the materials and that you retain all copyright notices contained in the materials. By downloading content from our website, you accept the terms of this agreement.


Presentation Transcript

1. Programming in C# AttributesCSE 494R(proposed course for 459 Programming in C#)Prof. Roger Crawfis

2. AttributesMany systems have a need to decorate code with additional information.Traditional solutionsAdd keywords or pragma’s to languageUse external files, e.g., .IDL, .DEFC# solution: Attributes Metadata – descriptive elements that decorate types and members (assembly, module, type, member, return value and parameter).

3. Attributes are classes; they inherit from System.AttributeAttach an attribute to a class, type, etc.Attributes - Exampleclass HelpUrlAttribute : System.Attribute { public HelpUrlAttribute(string url) { … } …}[HelpUrl(“http://SomeUrl/APIDocs/SomeClass”)]class SomeClass { … }

4. Attributes - ExampleAttributes can be queried at runtime by reflection:Type type = typeof(MyClass);foreach (object attr in type.GetCustomAttributes()) {     if (attr is HelpUrlAttribute)     {         HelpUrlAttribute help = (HelpUrlAttribute) attr;         myBrowser.Navigate(help.Url);     } }

5. Uses of Attributes in .NetProvide custom additions to metadata for managed typesSupport serializationSupport debugging and tracingSet COM+ attributesActivation, queuing, security, events, contexts, object pooling, synchronization, transactionsSupport creation of COM objectsSupport creation of .Net controlsSupport creation of Web ServicesCreate ATL Server code – essentially builds ISAPI filtersImplement performance countersImplement OLEDB consumers

6. Kinds of AttributesCustom attributesAdd entries to metadata but are not used by run-timeDistinguished custom attributesThese attributes have data stored in the assembly next to the items to which it applies.OneWay is a distinguished custom attribute that affects marshaling by the run-timePseudo custom attributesChanges, does not extend existing metadataSerializable is a pseudo custom attribute. It sets or resets the metadata flag tdSerializable

7. Defining Custom AttributesCreate a class marked with the AttributeUsage attribute [AttributeUsage(AttributeTargets.All, AllowMultiple=true)] class myAttribute : System.Attribute { … } Targets include:Assembly, Class, Delegate, Event, Field, Method, …, AllThe attribute class provides a constructor some state, and properties to retrieve the state.The state is stored in the metadata of the assembly that implements the attributed target.It is retrieved using the Reflection API.

8. Attributes are classes; they inherit from System.AttributeAttach an attribute to a class, type, etc.Attributes - Exampleclass HelpUrlAttribute : System.Attribute { public HelpUrlAttribute(string url) { … } …}[HelpUrl(“http://SomeUrl/APIDocs/SomeClass”)]class SomeClass { … }Note, it is allowed and customary to remove the Attribute suffix from the type name.

9. Provided Attributes in .Net[CLSCompliant(true)] - class fails to compile if not compliant[Conditional(“Debug”)] - won’t get called unless Debug defined[Assembly: AssemblyTitle(“…”)] - assembly descriptions[Assembly: AssemblyVersion(“1.2”)][DllImport(“kernel32.dll”)] - accessing unmanaged global functionpublic static extern int Beep(int freq, int dur);[Serializable()] - enabling serializationpublic class myClass { … }[OneWay()] - marshal only to remote objectpublic void myFunc(string msg) { … }[Synchronization()] - allow access by one thread at a timeclass SomeClass : ContextBoundObject { … }[Obsolete()] - generates a compiler error when used

10. Design-Time and Security AttributesAttributes used with user defined controls[Category(“Custom Properties”)] - makes property page category[DefaultEvent(myEvent)] - double click on control to wire up[Description(“myPropertDesc”)] - description shown when selected[ToolBoxBitmap(“myBitMap.bmp”)] – defines bitmap used in toolboxDeclarative security settings[FileIOPermission(SecurityAction.Deny, Read=@”c:\Windows\System32”)]public in ReadFile(string path) { … }

11. Preprocessor DirectivesC# provides preprocessor directives that serve a number of functionsUnlike C++, there is not a separate preprocessorThe “preprocessor” name is preserved only for consistency with C++Some C++ preprocessor features removed:#include: Not neededMacro version of #define: removed for clarity

12. Preprocessor DirectivesDirectiveDescription#define, #undefDefine and undefine conditional symbols#if, #elif, #else, #endifConditionally skip sections of code#error, #warningIssue errors and warnings#region, #endDelimit outline regions#lineSpecify line number

13. #define Debug public class Debug {   [Conditional("Debug")]   public static void Assert(bool condition, String msg) {     if (!condition) {       throw new AssertionException(msg);     }   }   void DoSomething() {     ...     // If Debug is not defined, the next line is     // not even called     Assert((x == y), “X should equal Y”);     ...   }} Conditional Compilation

14. Programming in C# AttributesCSE 494R(proposed course for 459 Programming in C#)Prof. Roger Crawfis