160 likes | 295 Views
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
E N D
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’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).
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 { … }
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); } }
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
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
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.
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 { … }
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
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) { … }
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
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”); ... } }
Programming in C#Attributes CSE 494R (proposed course for 459 Programming in C#) Prof. Roger Crawfis