using System;
using System.Diagnostics;
using System.Reflection;

namespace ConsoleApplication4
{
class Program
{
static void Main(string[] args)
{
var service = new RenderingService();
var type = service.GetType();
// .NET 4.5 way
var testableAttribute = type.GetCustomAttribute<TestableAttribute>();
if( testableAttribute != null )
{
Debug.Print( $"{type} has been marked as testable, switch value is {testableAttribute.On}");
}

// Older ways
var attribute = Attribute.GetCustomAttribute( type, typeof( TestableAttribute ) );
if( attribute != null )
{
Debug.Assert( attribute.GetType() == typeof( TestableAttribute ) ); // Can this assertion ever fire???
testableAttribute = attribute as TestableAttribute;
Debug.Assert( testableAttribute != null ); // Can this assertion ever fire ???
Debug.Print($"{type} has been marked as testable, switch value is {testableAttribute.On}");
}
}
}

[Testable(true)]
class RenderingService
{

}

[Testable( false )]
class PersistenceService
{

}

&nbsp;

[AttributeUsage( AttributeTargets.Class, Inherited = false, AllowMultiple = false)]
public class TestableAttribute : Attribute
{
private readonly bool _on;

public TestableAttribute( bool on )
{
_on = on;
}

public bool On => _on;
}
}

Advertisements