Girish, As you discovered, the attribute declaration does not cause the constructor to execute. You would need to call GetCustomAttribute on each member in order for the constructor of the corresponding attribute to be called.
According to Essential .NET, "Custom attributes are stored as passive BLOBs in the CLR metadata. These BLOBs represent serialized constructor calls to the attribute type... Calling GetCustomAttributes causes the serialized attribute constructors to execute as the attribute objects are instantiated from the metadata prior to your code seeing them." Stepping through the attached code illustrates this. Wally using System; using System.Reflection; class MyAttribute : Attribute { static int counter = 0; public MyAttribute() { Console.WriteLine("In constructor of attribute #{0}.", ++MyAttribute.counter); } } [MyAttribute] class MyClass : Object { [MyAttribute] public int i; [MyAttribute] public int j; } class MyApp { static void Main() { Type myType = typeof(MyClass); MyClass myClass = new MyClass(); MemberInfo[] memberInfos = myType.GetMembers(); foreach(MemberInfo mi in memberInfos) { // Custom attribute constructor called // in the following method mi.GetCustomAttributes(false); } } } -----Original Message----- From: Unmoderated discussion of advanced .NET topics. [mailto:[EMAIL PROTECTED] On Behalf Of Girish Jain Sent: Tuesday, January 18, 2005 7:19 AM To: ADVANCED-DOTNET@DISCUSS.DEVELOP.COM Subject: [ADVANCED-DOTNET] When does the attribute contructor gets executed?? Hi All, I have written a custom attribute and applied it to the public fields/properties of a class. This attribute actually maintains certain data per **Type**. In the constructor of this attribute class I am adding data to a static HashTable object, declared in the attribute class (Certainly, after checking that it does not already exist for the given Type) For example : public class A { [MyCustom("some data...")] public int i; [MyCustom("some data...")] public string Name { get { return this._ColName; } set { this._ColName = value; } } } I expect the attribute constructor to have already executed by the time I create the first instance of the class A. But it is not happening. Can anybody tell me when does the constructor for the attribute gets executed? Thanks in advance Regards, Girish Jain _________________________________________________________________ Redefine team work. Discover your true potential. http://www.microsoft.com/india/office/experience/ With the MS product suite. =================================== This list is hosted by DevelopMentorR http://www.develop.com View archives and manage your subscription(s) at http://discuss.develop.com =================================== This list is hosted by DevelopMentorŪ http://www.develop.com View archives and manage your subscription(s) at http://discuss.develop.com