4

I have a generic class which needs to use the name of one of its type arguments in a class attribute. I don't know how to access the class name in that context

I've tried using typeof(TMsg).Name but VS shows an error saying

An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type

Currently my code looks like this:

[MessageBase(typeof(TMsg).Name)]
    public abstract class DDSMessageAbstract<TMsg/*, TReader, TWriter, TMsgBase, TSupport*/> : MessageBaseForDDS
    where TMsg : new()
...

My question is, is there a way for me to use the actual name of TMsg or must I define this attribute for each inheriting class?

9
  • What is MessageBase? Can you modify it? Commented Jun 12, 2019 at 14:26
  • Change [MessageBase(typeof(TMsg).Name)] to [MessageBase(typeof(TMsg))]. Commented Jun 12, 2019 at 14:26
  • @HimBromBeere I can't change existing code but I can for example add a constructor Commented Jun 12, 2019 at 14:44
  • 1
    @ZoharPeled That would still show an error, as I can't use "typeof" inside an attribute Commented Jun 12, 2019 at 14:44
  • @Efi can you change the class that uses the attribute? Somewhere in your code there must be a place where you have the instance of your class inspected to check if your class was decorated with an attribute. There using the instance get the type and extract the generic type (doing so you get the name). Commented Jun 12, 2019 at 14:50

1 Answer 1

3

The short answer might be you could not do that.

First, the generics is for your class instead of your attribute. so you can't use

MessageBase(typeof(TMsg)

The values into attributes are limited to simple types; for example, basic constants (including strings) and typeof.

From ECMA 334v4:

§24.1.3 Attribute parameter types

The types of positional and named parameters for an attribute class are limited to the attribute parameter types, which are:

  • One of the following types: bool, byte, char, double, float, int, long, short, string.
  • The type object.
  • The type System.Type.
  • An enum type, provided it has public accessibility and the types in which it is nested (if any) also have public accessibility.
  • Single-dimensional arrays of the above types.

ECMA-334

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.