473,656 Members | 2,824 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

HOWTO?: enumerating custom attributes

I've recently 'discover' the wonders of custom attributes and
reflection. There's one aspect that has stumping me and I've been
unable to find samples in the docs or on the web.

I have fields in a class which have zero, one or more custom attributes
associated with each field. I'd like to get a list of the attributes
present for a given field, and then iterate over them to find
associated values.

Where I've coded for the presence of one attribute I've used:

FieldInfo[] Fields = TypeData.GetFie lds(BindingFlag s.Instance |
BindingFlags.No nPublic);

foreach (FieldInfo Field in Fields)
{
if (!Attribute.IsD efined(Field, typeof(MyAttrib ute)))
{
Console.WriteLi ne(Field.Name)
}
else
{
MyAttribute TheAttribute =
(MyAttribute)Fi eld.GetCustomAt tributes(typeof (Field), false)[0];

if (0 == MyAttribute.Nam e.Length) Console.WriteLi ne(Field.Name);
else Console.WriteLi ne(MyAttribute. Name);
}
}

I can see how this works - I'm telling it the type of attribute
(MyAttribute) to look for. What I cant find the syntax for is to
'.GetCustomAttr ibutes" where I don't already know the type.
Can anyone help please?

Nov 29 '06 #1
4 1816
da********@wild air.net wrote:
Field.GetCustom Attributes(type of(Field), false)[0];
I can see how this works - I'm telling it the type of attribute
(MyAttribute) to look for. What I cant find the syntax for is to
'.GetCustomAttr ibutes" where I don't already know the type.
This is a strange question. If you found GetCustomAttrib utes, surely
you also saw the overload that doesn't take a Type parameter?

GetCustomAttrib utes(bool) returns all the attributes, regardless of
type. The bool parameter specifies whether the array should include
inherited attributes or not.

--

..NET 2.0 for Delphi Programmers
www.midnightbeach.com/.net
What you need to know.
Nov 29 '06 #2

Jon Shemitz wrote:
da********@wild air.net wrote:
Field.GetCustom Attributes(type of(Field), false)[0];
I can see how this works - I'm telling it the type of attribute
(MyAttribute) to look for. What I cant find the syntax for is to
'.GetCustomAttr ibutes" where I don't already know the type.

This is a strange question. If you found GetCustomAttrib utes, surely
you also saw the overload that doesn't take a Type parameter?

GetCustomAttrib utes(bool) returns all the attributes, regardless of
type. The bool parameter specifies whether the array should include
inherited attributes or not.

--
Jon,

You're right - that overload is right there in the docs. I must have
stared at that page over half a dozen times and didn't see it. Thanks
for helping me see the obvious.

Nov 29 '06 #3
Hi,
I have fields in a class which have zero, one or more custom attributes
associated with each field. I'd like to get a list of the attributes
present for a given field, and then iterate over them to find
associated values.
<snip>

There are a few issues with your code, some of which will prevent it from
compiling. Try this instead:

public static void DisplayObsolete Fields(Type type)
{
FieldInfo[] fields = type.GetFields(
BindingFlags.In stance | BindingFlags.No nPublic);

Type attributeType = typeof(Obsolete Attribute); // for testing

foreach (FieldInfo field in fields)
{
Attribute[] attributes =
Attribute.GetCu stomAttributes( field, attributeType, false);

if (attributes.Len gth == 0)
Console.WriteLi ne("{0}: MyAttribute not defined", field);
else
{
foreach (ObsoleteAttrib ute attribute in attributes)
{
Console.WriteLi ne("{0}: MyAttribute(Mes sage={1})",
field, attribute.Messa ge);
}
}
}
}
On a side note, I recommend that you use lower camel case for local variable
names so that it's obvious you're not using static properties and methods
and to prevent conflicts with classes of the same name.

--
Dave Sexton
Nov 30 '06 #4
Hi,

In my example, I forgot to change "MyAttribut e" to "Obsolete" in a couple of
string literals, sorry.

--
Dave Sexton

<da********@wil dair.netwrote in message
news:11******** *************@h 54g2000cwb.goog legroups.com...
I've recently 'discover' the wonders of custom attributes and
reflection. There's one aspect that has stumping me and I've been
unable to find samples in the docs or on the web.

I have fields in a class which have zero, one or more custom attributes
associated with each field. I'd like to get a list of the attributes
present for a given field, and then iterate over them to find
associated values.

Where I've coded for the presence of one attribute I've used:

FieldInfo[] Fields = TypeData.GetFie lds(BindingFlag s.Instance |
BindingFlags.No nPublic);

foreach (FieldInfo Field in Fields)
{
if (!Attribute.IsD efined(Field, typeof(MyAttrib ute)))
{
Console.WriteLi ne(Field.Name)
}
else
{
MyAttribute TheAttribute =
(MyAttribute)Fi eld.GetCustomAt tributes(typeof (Field), false)[0];

if (0 == MyAttribute.Nam e.Length) Console.WriteLi ne(Field.Name);
else Console.WriteLi ne(MyAttribute. Name);
}
}

I can see how this works - I'm telling it the type of attribute
(MyAttribute) to look for. What I cant find the syntax for is to
'.GetCustomAttr ibutes" where I don't already know the type.
Can anyone help please?

Nov 30 '06 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
454
by: Doug Holland | last post by:
Often you see code where an empty interface is used to indicate something about the class that realizes it. In the .NET world this can be done with custom attributes too, so which is better: public class SomeClass : IEmptyInterface or
1
2138
by: Bret Pehrson | last post by:
I've converted a non-trivial C++ library to managed, and get the following unhelpful linker error: Assignment.obj : error LNK2022: metadata operation failed (80131195) : Custom attributes are not consistent: (0x0c0001a5). Display.obj : error LNK2022: metadata operation failed (80131195) : Custom attributes are not consistent: (0x0c000108). The help for LNK2022 is completely useless:
3
2140
by: Edward Diener | last post by:
I understand the syntax of custom attributes, but I have no idea what they are supposed to do. Anyone care to give me a clue as to their functionality ?
1
4204
by: Tamas Demjen | last post by:
I started to experiment with VC++ 2005 Beta1. So far everything went fine, and already have a working project, but soon I realized that the compiler was ancient (not supporting half of the C++/CLI standard). So I downloaded the VC++ 2005 Tools Refresh (http://tinyurl.com/5mdq2). After that I tried to do a full rebuild, but my project wouldn't link anymore. I get the following errors: MSVCMRTD.lib(mstartup.obj) : error LNK2022: metadata...
3
3532
by: The Developer | last post by:
Hi All, I have a web application where I am adding a custom attribute to my ASP.NET text box control and changing value of that attribute at client side using JavaScript. My problem is that changed value of that custom attribute is not reflecting back at server side. Any ideas about this problem? Server side code: private void Page_Load(object sender, EventArgs e) { if (this.IsPostBack == false)
0
1037
by: Sanjay Pais | last post by:
This is an extension of an earlier post I have created a custom text box and compiled it and dropped it into my toolbox. However when I change the value of my custom property in design mode and switch between design mode to page source and back to design mode i am unable to retrieve the property value I set. Also the property setting in the html page is lost. Thsi is the error I get **********************************...
1
1698
by: Sanjay Pais | last post by:
I built a custom control for all the basic web.ui.controls like textbox, label, checkbox etc etc. I added my custom attribute called ApplySecurity to the html in the page. However, when I cycle through the controls on the page using this code, I cant seem to be able to access the Attribute collection. However, if I were to add the tag to a regular TextBox, the Attribute is available. My recursive function looks like this:...
3
3186
by: Mark R. Dawson | last post by:
Hi all, I am trying to get custom attributes from a property. I can do this if I pass in the name of the property i.e. "Name" to the reflection methods, but if I pass in set_Name which is what the set piece of the Name property gets compiled to, which I am getting from the stack trace, then the attributes are not returned. For example, Class Person has a property called "Name" which has a custom attribute decorating it. Inside the set...
2
2520
by: prabhupr | last post by:
Hi Folks I was reading this article (http://www.dotnetbips.com/articles/displayarticle.aspx?id=32) on "Custom Attribute", written by Bipin. The only thing I did not understand in this article is the usage of "Custom Attribute" in real life project. Can somebody please help me understand where are these informations really helpful in Development Environment; may be a few example(s) will help me understand.
0
8297
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8816
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8717
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
7311
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6162
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4150
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4300
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
1930
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1600
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.