1 / 14

Programming in C# Attributes

Programming in C# Attributes. 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 pragma’s to language Use external files, e.g., .IDL, .DEF

yule
Download Presentation

Programming in C# Attributes

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


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

  2. Attributes • Many systems have a need to decorate code with additional information. • Traditional solutions • Add keywords or pragma’sto language • Use external files, e.g., .IDL, .DEF • C# solution: Attributes • Metadata – descriptive elements that decorate types and members (assembly, module, type, member, return value and parameter).

  3. Attributes - Example • Attributes are classes; they inherit from System.Attribute • Attach an attribute to a class, type, etc. classHelpUrlAttribute : System.Attribute { publicHelpUrlAttribute(string url) { … } … } [HelpUrl(“http://SomeUrl/APIDocs/SomeClass”)] classSomeClass { … }

  4. Attributes - Example • Attributes can be queried at runtime by reflection: Typetype = typeof(MyClass); foreach (objectattrintype.GetCustomAttributes()) { if (attrisHelpUrlAttribute)     { HelpUrlAttribute help = (HelpUrlAttribute) attr; myBrowser.Navigate(help.Url);     } }

  5. Uses of Attributes in .Net • Provide custom additions to metadata for managed types • Support serialization • Support debugging and tracing • Set COM+ attributes • Activation, queuing, security, events, contexts, object pooling, synchronization, transactions • Support creation of COM objects • Support creation of .Net controls • Support creation of Web Services • Create ATL Server code – essentially builds ISAPI filters • Implement performance counters • Implement OLEDB consumers

  6. Kinds of Attributes • Custom attributes • Add entries to metadata but are not used by run-time • Distinguished custom attributes • These 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-time • Pseudo custom attributes • Changes, does not extend existing metadata • Serializable is a pseudo custom attribute. It sets or resets the metadata flag tdSerializable

  7. Defining Custom Attributes • Create a class marked with the AttributeUsageattribute [AttributeUsage(AttributeTargets.All, AllowMultiple=true)] classmyAttribute : System.Attribute { … } • Targets include: • Assembly, Class, Delegate, Event, Field, Method, …, All • The 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 - Example • Attributes are classes; they inherit from System.Attribute • Attach an attribute to a class, type, etc. classHelpUrlAttribute : System.Attribute { publicHelpUrlAttribute(string url) { … } … } Note, it is allowed and customary to remove the Attribute suffix from the type name. [HelpUrl(“http://SomeUrl/APIDocs/SomeClass”)] classSomeClass { … }

  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 intBeep(int freq, intdur); • [Serializable()] - enabling serializationpublic class myClass { … } • [OneWay()] - marshal only to remote objectpublic void myFunc(stringmsg) { … } • [Synchronization()] - allow access by one thread at a timeclassSomeClass : ContextBoundObject { … } • [Obsolete()] - generates a compiler error when used

  10. Design-Time and Security Attributes Attributes 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 toolbox Declarative security settings • [FileIOPermission(SecurityAction.Deny, Read=@”c:\Windows\System32”)]public in ReadFile(string path) { … }

  11. Preprocessor Directives • C# provides preprocessor directives that serve a number of functions • Unlike C++, there is not a separate preprocessor • The “preprocessor” name is preserved only for consistency with C++ • Some C++ preprocessor features removed: • #include: Not needed • Macro version of #define: removed for clarity

  12. Preprocessor Directives

  13. Conditional Compilation #define Debug publicclassDebug {   [Conditional("Debug")] publicstaticvoid Assert(bool condition, Stringmsg) { if (!condition) { thrownewAssertionException(msg);     }   } voidDoSomething() {     ... // If Debug is not defined, the next line is // not even called     Assert((x == y), “X should equal Y”);     ...   } }

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

More Related