Reputation: 579
For example, the following simple code detect if the term "Test" had been defined, to determin whether or not we should run the function.
[Conditional("Test")]
public static void print() {
Console.WriteLine("Test_Conditional");
}
How doest it work internally? I found the source code for the ConditonalAttribute class
[Serializable]
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, AllowMultiple=true)]
[System.Runtime.InteropServices.ComVisible(true)]
public sealed class ConditionalAttribute : Attribute
{
public ConditionalAttribute(String conditionString)
{
m_conditionString = conditionString;
}
public String ConditionString {
get {
return m_conditionString;
}
}
private String m_conditionString;
}
This class seems do nothing to determine whether the m_conditionString has been defined. I tried to create my own attribute class the same as ConditionalAttribute but it did not work like ConditionalAttribute. Here is my own attribute class(the difference is just the name of the class)
[Serializable]
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, AllowMultiple=true)]
[System.Runtime.InteropServices.ComVisible(true)]
public sealed class TestAttribute : Attribute
{
public TestAttribute (String conditionString)
{
m_conditionString = conditionString;
}
public String ConditionString {
get {
return m_conditionString;
}
}
private String m_conditionString;
}
How does it work internally?
Upvotes: 0
Views: 300
Reputation: 68760
The is a special attribute, which the compiler is aware of. At compile-time, the compiler parses your methods and checks whether this specific attribute was defined. To investigate how the functionality is implemented, you'd have to look into the compiler's source code - the Visual C# compiler that comes bundled with VS2013 is not open source, but Roslyn is, you can give that a try.
This is also why your custom attribute doesn't do anything.
In general, attributes don't have much logic in them - they're usually just simple markers. It's the code that scans for these attributes that implements the main logic.
Upvotes: 2