• 0

[C#] Getting Attribute's Target Name..?


Question

is it possible to retrieve the name of the target ... member that an attribute is applied to?

for ex,

[STAThread] void Main() { }

[Obsolete] int OldMethod() { }

[SomeAttr] private int AField;

[SomeAttr] private int AProperty { get; set; }

i would like to get the name "Main" / "OldMethod" / "AField" / "AProperty" from code

but the attributes themselves don't directly reference their targets

any suggestions?

Link to comment
https://www.neowin.net/forum/topic/561585-c-getting-attributes-target-name/
Share on other sites

5 answers to this question

Recommended Posts

  • 0

You need to use Reflection to do it. (using System.Reflection needs to be at the top for this)

Create a Type object corresponding to your class, then iterate through each member of GetMembers()

		class SomethingAttribute : Attribute { }
		class Test
		{
			[Obsolete]
			public void DoSomething() { }
			[Something]
			public void DoSomethingElse() { }
		}
		static void Main()
		{
			Type t = typeof(Test);
			foreach (MemberInfo m in t.GetMembers())
			{
				object[] a = m.GetCustomAttributes(false);
				if (a.Length != 0)
				{
					Console.WriteLine("Member {0} has the following attributes: ", m.Name);
					foreach (Attribute x in a)
					{
						Console.WriteLine(x.ToString());
					}
				}
			}
			Console.ReadLine();
		}

You can fine tune it by saying m.GetCustomAttributes(typeof(ObsoleteAttribute), false), that will ensure that it only returns Attributes that are Obsolete. So, for example. you can write:

if (m.GetCustomAttributes(typeof(ObsoleteAttribute), false).Length != 0) 
{
Console.WriteLine("{0} is obsolete.", m.Name);
}

  • 0

this is what i've got. i want the attribute itself to be able to figure out the name of its target

[AttributeUsage(AttributeTargets.Property)]
public class DbParamAttribute : Attribute
{
	public readonly string ParameterName;
	public readonly bool IsUpdatable;

	public DbParamAttribute() : this(true) { }
	public DbParamAttribute(bool updatable)
	{
		throw new NotImplementedException();

		//how do i have the attribute figure
		//out the name of its target?
		ParameterName = null;
		IsUpdatable = updatable;
	}

	//provides explicit setting of db parameter name
	public DbParamAttribute(string parameter) : this(parameter, true) { }
	public DbParamAttribute(string parameter, bool updatable)
	{
		ParameterName = parameter;
		IsUpdatable = updatable;
	}
}

  • 0

I'm so sorry. I still don't follow what you need, exactly.

Your code won't work because of the 'readonly' modifier on the variables. This should help there....but I'm sorry. I still can't figure out what you need here:

		//how do i have the attribute figure
		//out the name of its target?
		ParameterName = null;
		IsUpdatable = updatable;

private int x;
public int X
{
get
{
return x;
}
private set
{
x = value;
}
}

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.
  • Posts

    • Listen, adrynalyne - You're trolling me (I've known this for months). If you have something meaningful to say - say it, don't ask as if you know something, becauser you know sh*t. Ok?
    • SMPlayer 25.6.0 by Razvan Serea SMPlayer intends to be a complete front-end for MPV/MPlayer , from basic features like playing videos, DVDs, and VCDs to more advanced features like support for MPlayer filters and more. One of the most interesting features of SMPlayer: it remembers the settings of all files you play. So you start to watch a movie but you have to leave... don't worry, when you open that movie again it will resume at the same point you left it, and with the same settings: audio track, subtitles, volume... Other additional interesting features: Configurable subtitles. You can choose font and size, and even colors for the subtitles. Audio track switching. You can choose the audio track you want to listen. Works with avi and mkv. And of course with DVDs. Seeking by mouse wheel. You can use your mouse wheel to go forward or backward in the video. Video equalizer, allows you to adjust the brightness, contrast, hue, saturation and gamma of the video image. Multiple speed playback. You can play at 2X, 4X... and even in slow motion. Filters. Several filters are available: deinterlace, postprocessing, denoise... and even a karaoke filter (voice removal). Audio and subtitles delay adjustment. Allows you to sync audio and subtitles. Advanced options, such as selecting a demuxer or video & audio codecs. Playlist. Allows you to enqueue several files to be played one after each other. Autorepeat and shuffle supported too. Preferences dialog. You can easily configure every option of SMPlayer by using a nice preferences dialog. Possibility to search automatically for subtitles in opensubtitles.org. Translations: currently SMPlayer is translated into more than 20 languages, including Spanish, German, French, Italian, Russian, Chinese, Japanese.... It's multiplatform. Binaries available for Windows and Linux. SMPlayer is under the GPL license. SMPlayer 25.6.0 changelog: Fix play/pause button. Some fixes to stop the screensaver on Linux. Fixed some issues related to disc playback. Various bug fixes and stability improvements. Download: SMPlayer 25.6.0 (64-bit) | Portable | ~40.0 MB (Open Source) Download: SMPlayer 25.6.0 (32-bit) | Portable Links: SMPlayer Website | Mac OS | Screenshot Get alerted to all of our Software updates on Twitter at @NeowinSoftware
    • Mozilla never had the funding resources to promote their stuff the way Microsoft and Google do. As simple as 1-2-3.
    • ...Microsoft says that Edge is better for your Windows PC than Google's Chrome, as it is a "Microsoft product" that "integrates closely with Microsoft Windows," which helps with "performance benefits."... Yeah, right! Microsoft is still trying hard to convince everyone about everything it makes...
    • This is the curse of Linux on the desktop, the development and maintenance manpower is spread out across countless distributions. The same thing has to be integrated many times.
  • Recent Achievements

    • Week One Done
      Al_ earned a badge
      Week One Done
    • Week One Done
      MadMung0 earned a badge
      Week One Done
    • Reacting Well
      BlakeBringer earned a badge
      Reacting Well
    • Reacting Well
      Lazy_Placeholder earned a badge
      Reacting Well
    • Dedicated
      Epaminombas earned a badge
      Dedicated
  • Popular Contributors

    1. 1
      +primortal
      474
    2. 2
      +FloatingFatMan
      273
    3. 3
      ATLien_0
      242
    4. 4
      snowy owl
      211
    5. 5
      Edouard
      182
  • Tell a friend

    Love Neowin? Tell a friend!