• 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

    • Brave 1.79.123 by Razvan Serea Brave Browser is a lightning-fast, secure web browser that stands out from the competition with its focus on privacy, security, and speed. With features like HTTPS Everywhere and built-in tracker blocking, Brave keeps your online activities safe from prying eyes. Brave is one of the safest browsers on the market today. It blocks third-party data storage. It protects from browser fingerprinting. And it does all this by default. Speed - Brave is built on Chromium, the same technology that powers Google Chrome, and is optimized for speed, providing a fast and responsive browsing experience. Brave Browser also features Brave Rewards, a system that rewards users with Basic Attention Tokens (BAT) for viewing opt-in ads. This innovative system provides an alternative revenue model for content creators and a way to support the Brave community. Brave 1.79.123 changelog: Leo Improved citation UI. (#45761) General [Security] Fixed missing DDNS navigation throttle for subframes as reported on HackerOne by newfunction. (#46703) Fixed crash which occurred when clicking on the “View site information” icon in the address bar while having “Don’t allow sites to scroll and zoom shared tabs” enabled. (#46566) Fixed crash which occurred with the “Save autofill” prompt in certain cases. (#45546) Upgraded Chromium to 137.0.7151.104. (#46712) (Changelog for 137.0.7151.104) Download: Brave Browser 64-bit | 1.2 MB (Freeware) Download: Brave Browser 32-bit View: Brave Homepage | Offline Installers | Screenshot Get alerted to all of our Software updates on Twitter at @NeowinSoftware
    • A summary of the article shouldn't be an issue in theory, as the information is all based within the document itself. The problem with a lot of AI models is that they are trained off both Wikipedia as a primary source and other secondary websites which have less reliable information. As an encyclopaedia it is no doubt going to have bias in one way or another, all encyclopaedias do. The difference is that there is a process for a lot of this information to be figured out whether or not it is an opinion, or the source of that information, and to be aware of the possible bias in the first place, even your own bias as a reader. The way many people understand languages these days is quite limited, particularly in certain areas of the world. This is obvious in many types of "journalism" where some articles are thinly disguised opinion pieces, Where language is carefully curated to push a point of view despite it looking like fact. This is partly why a lot of the Western world is now so divided.
    • I paid for a year subscription, starting in December, I think. I like the user-friendliness and assets like royalty-free music and sounds. But they need to fix some of the horrific bugs before they start adding more features. For starters, you should be able to drag stuff around the timeline without it completely obliterating transitions, synchronization timing, and clip lengths. If you already set up footage and audio how you want, and try to insert more by sliding content to the right, you'll have to clean it all up again. The scroll wheel constantly stops working, and you have to minimize the window and restore it to get it back. When selecting text at the top right in special text tools, it glitches and goes to "copy" mode with a weird pop-up on top of your cursor and you can't type. These are more important than AI tools and new features. Microsoft, start by making your product less painful to use.
    • 🙄 Whats the need to launder? Do you have any reputable sources?
    • Thanks, I'll download it and see how it goes. Gonna be tough. I've used Nova Launcher for around 10+ years I think.
  • Recent Achievements

    • Apprentice
      Adrian Williams went up a rank
      Apprentice
    • Reacting Well
      BashOrgRu earned a badge
      Reacting Well
    • Collaborator
      CHUNWEI earned a badge
      Collaborator
    • Apprentice
      Cole Multipass went up a rank
      Apprentice
    • Posting Machine
      David Uzondu earned a badge
      Posting Machine
  • Popular Contributors

    1. 1
      +primortal
      517
    2. 2
      ATLien_0
      259
    3. 3
      +Edouard
      191
    4. 4
      +FloatingFatMan
      174
    5. 5
      snowy owl
      133
  • Tell a friend

    Love Neowin? Tell a friend!