• 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

    • I see the Winblows 11 BETA testing continues. This is just Windows 10 all over again. Oh well, everything is still smooth sailing over here on Windows 10 21H2 LTSC. You unpaid sheep BETA testers be sure to let us know when you get done BETA testing Winblows 11 for the rest of us. 🤣
    • What do you expect? Windows 11 is still in BETA. This is Windows 10 all over again. M$ doesn't hire people to do BETA testing anymore. They just let all the dumb sheep with FOMO do all the BETA testing for them. It's the same dumb sheep who use self-checkout at the store and do someone else's job for FREE! All while the worker who's getting paid just stands there and watches them. 🤣 🤡
    • Pet peeve: Microsoft using scaling options to get around the fact they removed font size settings, as if that's somehow acceptable to do. Thankfully third party apps still can adjust font sizes just fine, even though it often randomly resets on OS updates. And the funny thing is that not only are the scaling options horrible crutches, but they only work in some applications. And, ironically enough, even some apps from Microsoft themselves have hardcoded tiny fonts in certain dialogs in them. Example - certain parts of MS Office apps UI.
    • Unofficial script does the most useful official Windows 11/10 repairs you want automatically by Sayan Sen IT admins and system admins, and even home users have to run various Windows diagnostic runs from time to time in order to iron out or work around system problems. Last year, Microsoft published a guidance piece about various such native Windows apps, tools and utilities they include the like of Task Manager, Registry Editor, and more. Aside from them, Windows also comes with SFC (System File Checker) and DISM (Deployment Image Servicing and Management) to scan and fix corrupt and missing system files. Besides those, various other ways to help and diagnose network issues related to DNS (Domain Name System), among others, also exists. In order to save time running these, a Reddit user has created a new tool that automates all of these into a single package. The author writes that the Batch script (.BAT file) they have developed is "basically a one-stop script that can help clean up your system, run built-in diagnostics, fix common network issues, and generate system reports." The script is based on native Windows tools like netsh, ipconfig, systeminfo, among others, and the idea behind this is essentially to save time. The tool can be of help with Windows Update repairs, among others, something we all know is pretty common, and even Microsoft's own support articles may not prove to be helpful. Here is everything the utility can do for you: Run SFC, DISM, CHKDSK from a single menu Restart network adapters with auto-detection Flush or set DNS (Google, Cloudflare, or custom) Windows Update repair (resets services + cache) Generate system reports (saved as .txt files on Desktop) Show installed drivers Clean up temp files Registry backup and restore (manual) The latest version of the utility is now available for download on GitHub. The new version fixes issues related to admin privileges. As the script requires it to be run as an admin, it now restart itself to work in admin mode even if a user forgot to run it as an administrator. To download it, head over to its GitHub page here. The utility is named Windows Maintenance Tool. As always, though, make sure to back up your PC as this is an unofficial third-party app, and it's better if you test it first in a VM. Source: Lil_Batti (Reddit)
    • Come the hell on, do we need clickbait titles? "Overwatch 2" - 11 characters "a popular multiplayer hero shooter" - 34 characters What's the purpose here - delivering news or titles for clicks? I think we all know the answer. You're straying into "Number 7 on this list will SHOCK you" territory and while it may work on some crappy sites, this is why they are crappy sites. Just tell the story! Go back and look at popular articles that made Neowin what it was. Did they have headlines of "New OS from major technology conglomerate has astonishing new feature" or is it likely to tell the story succinctly and then elaborate within the content?
  • Recent Achievements

    • One Month Later
      CoolRaoul earned a badge
      One Month Later
    • First Post
      Kurotama earned a badge
      First Post
    • Collaborator
      Carltonbar earned a badge
      Collaborator
    • Explorer
      MusicLover2112 went up a rank
      Explorer
    • Dedicated
      MadMung0 earned a badge
      Dedicated
  • Popular Contributors

    1. 1
      +primortal
      508
    2. 2
      ATLien_0
      270
    3. 3
      +FloatingFatMan
      245
    4. 4
      +Edouard
      201
    5. 5
      snowy owl
      168
  • Tell a friend

    Love Neowin? Tell a friend!