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


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
class HelpUrlAttribute : System.Attribute {
public HelpUrlAttribute(string url) { … }
…
}

Attach an attribute to a class, type, etc.
[HelpUrl(“http://SomeUrl/APIDocs/SomeClass”)]
class SomeClass { … }
Attributes - Example

Attributes 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);
}
}
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


Distinguished custom attributes



Add entries to metadata but are not used by run-time
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 AttributeUsage
attribute
[AttributeUsage(AttributeTargets.All, AllowMultiple=true)]
class myAttribute : 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
class HelpUrlAttribute : System.Attribute {
public HelpUrlAttribute(string url) { … }
…
Note, it is allowed and
}
customary to remove the
Attribute suffix from the type
name.

Attach an attribute to a class, type, etc.
[HelpUrl(“http://SomeUrl/APIDocs/SomeClass”)]
class SomeClass { … }
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 function
public static extern int Beep(int freq, int dur);
[Serializable()]
- enabling serialization
public class myClass { … }
[OneWay()]
- marshal only to remote object
public void myFunc(string msg) { … }
[Synchronization()]
- allow access by one thread at a time
class SomeClass : 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
Preprocessor Directives
Directive
Description
#define, #undef
Define and undefine conditional
symbols
#if, #elif, #else, #endif
Conditionally skip sections of code
#error, #warning
Issue errors and warnings
#region, #end
Delimit outline regions
#line
Specify line number
Conditional Compilation
#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”);
...
}
}
Programming in C#
Attributes
CSE 494R
(proposed course for 459 Programming in C#)
Prof. Roger Crawfis