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?

Efi Z
  • 182
  • 12

1 Answers1

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

D-Shih
  • 44,943
  • 6
  • 31
  • 51