• 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

    • Firefox 139.0.4 by Razvan Serea Firefox is a fast, full-featured Web browser. It offers great security, privacy, and protection against viruses, spyware, malware, and it can also easily block pop-up windows. The key features that have made Firefox so popular are the simple and effective UI, browser speed and strong security capabilities. Firefox has complete features for browsing the Internet. It is very reliable and flexible due to its implemented security features, along with customization options. Firefox includes pop-up blocking, tab-browsing, integrated Google search, simplified privacy controls, a streamlined browser window that shows you more of the page than any other browser and a number of additional features that work with you to help you get the most out of your time online. Download: Firefox 64-bit | Firefox 32-bit | ARM64 | ~60.0 MB (Freeware) Download: Firefox 139.0.4 for Linux | 64-bit | ~90.0 MB Download: Firefox for MacOS | 127.0 MB View: Firefox Home Page | Release Notes Get alerted to all of our Software updates on Twitter at @NeowinSoftware
    • Joplin 3.3.13 by Razvan Serea Joplin is a free, open source note taking and to-do application, which can handle a large number of notes organised into notebooks. The notes are searchable, can be copied, tagged and modified either from the applications directly or from your own text editor. Notes exported from Evernote can be imported into Joplin, including the formatted content (which is converted to Markdown), resources (images, attachments, etc.) and complete metadata (geolocation, updated time, created time, etc.). Plain Markdown files can also be imported. The notes can be securely synchronised using end-to-end encryption with various cloud services including Nextcloud, Dropbox, OneDrive and Joplin Cloud. Full text search is available on all platforms to quickly find the information you need. The app can be customised using plugins and themes, and you can also easily create your own. The application is available for Windows, Linux, macOS, Android and iOS. A Web Clipper, to save web pages and screenshots from your browser, is also available for Firefox and Chrome. Features Web Clipper for Firefox and Chrome. End To End Encryption (E2EE). Note history (revisions). Synchronisation with various services, including Nextcloud, Dropbox, WebDAV and OneDrive. Offline first, so the entire data is always available on the device even without an internet connection. Import Enex files (Evernote export format) and Markdown files. Export JEX files (Joplin Export format) and raw files. Support notes, to-dos, tags and notebooks. Sort notes by multiple criteria - title, updated time, etc. Support for alarms (notifications) in mobile and desktop applications. Markdown notes, which are rendered with images and formatting in the desktop and mobile applications. Support for extra features such as math notation and checkboxes. Choice of both Markdown and Rich Text (WYSIWYG) editors. File attachment support - images are displayed, other files are linked and can be opened in the relevant application. Inline display of PDF, video and audio files. Goto Anything feature. Search functionality. Geo-location support. Supports multiple languages. External editor support - open notes in your favorite external editor with one click in Joplin. Extensible functionality through plugin and data APIs. Custom CSS support for customisation of both the rendered markdown and overall user interface. Customisable layout allows toggling, movement and sizing of various elements. Keyboard shortcuts are editable and allow binding of most Joplin commands with export/import functionality. Joplin 3.3.13 changelog: Fixed: Fix printing (#12244) (#12240 by @personalizedrefrigerator) Download: Joplin 3.3.13 | Joplin Portable | ~300 MB (Open Source) Download: MacOS | Android | Linux | iOS View: Joplin Home Page | GitHub project page Get alerted to all of our Software updates on Twitter at @NeowinSoftware
    • Apple: lets take our inspiration from Windows 7/Vista and call it innovative
    • Nice! My $100 refurbished iPad 8 that I bought last year for a small project (and still runs like new cuz it's been mostly in storage the past several months) will get this v26 upgrade. I'm definitely gonna scope out OS26 on this device before upgrading my also-supported refurbished iPhone SE 3rd Gen (only got it for the 5G UW support).
    • Hello, The separate discussion about VLC has been moved to its own thread at  Regards, Aryeh Goretsky  
  • Recent Achievements

    • Dedicated
      MadMung0 earned a badge
      Dedicated
    • Rookie
      CHUNWEI went up a rank
      Rookie
    • Enthusiast
      the420kid went up a rank
      Enthusiast
    • Conversation Starter
      NeoToad777 earned a badge
      Conversation Starter
    • Week One Done
      VicByrd earned a badge
      Week One Done
  • Popular Contributors

    1. 1
      +primortal
      506
    2. 2
      ATLien_0
      267
    3. 3
      +FloatingFatMan
      257
    4. 4
      Edouard
      203
    5. 5
      snowy owl
      178
  • Tell a friend

    Love Neowin? Tell a friend!