Get the attribute of a class within this class

M

Michael

Hello all,

using System;

namespace Test
{
[AttributeUsage(AttributeTargets.Class,
AllowMultiple = false)]
public class FactoryAttribute : System.Attribute
{
public string Identifier { get { return id_; } }
private string id_;

public FactoryAttribute(string identifier)
{
id_ = identifier;
}
}

[FactoryAttribute("MaladieLundi")]
class Foo
{
}
}

Is it possible IN Foo to get the value of the identifier of
FactoryAttribute?

thanks in advance

Mike
 
C

Ciaran O''Donnell

Yes,
do this in a method:
FactoryAttribute fa =
(FactoryAttribute)this.GetType().GetCustomAttributes(typeof(FactoryAttribute), false);

be warned though that enumerating custom attributes is very processing
intensive. It is possibly the slowest reflection operation.
 
M

Michael

Yes,
do this in a method:
FactoryAttribute fa =
(FactoryAttribute)this.GetType().GetCustomAttributes(typeof(FactoryAttribute), false);

be warned though that enumerating custom attributes is very processing
intensive. It is possibly the slowest reflection operation.

OK, thank you for that answer.

And what is the way to do that from a static function?
 
J

Jon Skeet [C# MVP]

OK, thank you for that answer.

And what is the way to do that from a static function?

Use typeof(YourClassNameHere) instead of this.GetType().

Jon
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top