Roslyn - Type of TypedConstant.Value for a typeof expression

Viewed 533

If I have some source code with a typeof expression, eg, in an attribute, what should I cast the TypedConstant's Value property to? I can't find this information documented anywhere.

For example, I have the following source code:

class FooAttribute : Attribute
{
    public FooAttribute(Type type) {}
}

[Foo(typeof(int))]
class Bar {}

and I want to look at Foo's argument in my analyser:

[DiagnosticAnalyzer(LanguageNames.CSharp)]
class MyAnalyser : DiagnosticAnalyzer
{
    public override void Initialize(AnalysisContext context)
    {
        context.RegisterCompilationAction(LookAtFooArg);
    }

    private void LookAtFooArg(CompilationAnalysisContext context)
    {
        TypedConstant argumentTypedConstant = context.Compilation
            .GetTypeByMetadataName("Bar")
            .GetAttributes()
            .Single()
            .ConstructorArguments
            .Single();
        // Value here is typed as an object. What should I cast it to?
        var typeOfExpressionValue = argumentTypedConstant.Value;
    }
}
1 Answers
Related