summaryrefslogtreecommitdiff
path: root/src/mscorlib/src/System/Attribute.cs
blob: baa9a716388d83011205b3f5a0335d4ee5eaf725 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.



using System;
using System.Reflection;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Globalization;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Security;

namespace System
{
    [Serializable]
    [AttributeUsageAttribute(AttributeTargets.All, Inherited = true, AllowMultiple = false)]
    public abstract class Attribute
    {
        #region Private Statics

        #region PropertyInfo
        private static Attribute[] InternalGetCustomAttributes(PropertyInfo element, Type type, bool inherit)
        {
            Contract.Requires(element != null);
            Contract.Requires(type != null);
            Contract.Requires(type.IsSubclassOf(typeof(Attribute)) || type == typeof(Attribute));

            // walk up the hierarchy chain
            Attribute[] attributes = (Attribute[])element.GetCustomAttributes(type, inherit);

            if (!inherit)
                return attributes;

            // create the hashtable that keeps track of inherited types
            Dictionary<Type, AttributeUsageAttribute> types = new Dictionary<Type, AttributeUsageAttribute>(11);

            // create an array list to collect all the requested attibutes
            List<Attribute> attributeList = new List<Attribute>();
            CopyToArrayList(attributeList, attributes, types);

            //if this is an index we need to get the parameter types to help disambiguate
            Type[] indexParamTypes = GetIndexParameterTypes(element);


            PropertyInfo baseProp = GetParentDefinition(element, indexParamTypes);
            while (baseProp != null)
            {
                attributes = GetCustomAttributes(baseProp, type, false);
                AddAttributesToList(attributeList, attributes, types);
                baseProp = GetParentDefinition(baseProp, indexParamTypes);
            }
            Array array = CreateAttributeArrayHelper(type, attributeList.Count);
            Array.Copy(attributeList.ToArray(), 0, array, 0, attributeList.Count);
            return (Attribute[])array;
        }

        private static bool InternalIsDefined(PropertyInfo element, Type attributeType, bool inherit)
        {
            // walk up the hierarchy chain
            if (element.IsDefined(attributeType, inherit))
                return true;

            if (inherit)
            {
                AttributeUsageAttribute usage = InternalGetAttributeUsage(attributeType);

                if (!usage.Inherited)
                    return false;

                //if this is an index we need to get the parameter types to help disambiguate
                Type[] indexParamTypes = GetIndexParameterTypes(element);

                PropertyInfo baseProp = GetParentDefinition(element, indexParamTypes);

                while (baseProp != null)
                {
                    if (baseProp.IsDefined(attributeType, false))
                        return true;

                    baseProp = GetParentDefinition(baseProp, indexParamTypes);
                }
            }

            return false;
        }

        private static PropertyInfo GetParentDefinition(PropertyInfo property, Type[] propertyParameters)
        {
            Contract.Requires(property != null);

            // for the current property get the base class of the getter and the setter, they might be different
            // note that this only works for RuntimeMethodInfo
            MethodInfo propAccessor = property.GetGetMethod(true);

            if (propAccessor == null)
                propAccessor = property.GetSetMethod(true);

            RuntimeMethodInfo rtPropAccessor = propAccessor as RuntimeMethodInfo;

            if (rtPropAccessor != null)
            {
                rtPropAccessor = rtPropAccessor.GetParentDefinition();

                if (rtPropAccessor != null)
                {
                    // There is a public overload of Type.GetProperty that takes both a BingingFlags enum and a return type.
                    // However, we cannot use that because it doesn't accept null for "types".
                    return rtPropAccessor.DeclaringType.GetProperty(
                        property.Name,
                        BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly,
                        null, //will use default binder
                        property.PropertyType,
                        propertyParameters, //used for index properties
                        null);
                }
            }

            return null;
        }

        #endregion

        #region EventInfo
        private static Attribute[] InternalGetCustomAttributes(EventInfo element, Type type, bool inherit)
        {
            Contract.Requires(element != null);
            Contract.Requires(type != null);
            Contract.Requires(type.IsSubclassOf(typeof(Attribute)) || type == typeof(Attribute));

            // walk up the hierarchy chain
            Attribute[] attributes = (Attribute[])element.GetCustomAttributes(type, inherit);
            if (inherit)
            {
                // create the hashtable that keeps track of inherited types
                Dictionary<Type, AttributeUsageAttribute> types = new Dictionary<Type, AttributeUsageAttribute>(11);
                // create an array list to collect all the requested attibutes
                List<Attribute> attributeList = new List<Attribute>();
                CopyToArrayList(attributeList, attributes, types);

                EventInfo baseEvent = GetParentDefinition(element);
                while (baseEvent != null)
                {
                    attributes = GetCustomAttributes(baseEvent, type, false);
                    AddAttributesToList(attributeList, attributes, types);
                    baseEvent = GetParentDefinition(baseEvent);
                }
                Array array = CreateAttributeArrayHelper(type, attributeList.Count);
                Array.Copy(attributeList.ToArray(), 0, array, 0, attributeList.Count);
                return (Attribute[])array;
            }
            else
                return attributes;
        }

        private static EventInfo GetParentDefinition(EventInfo ev)
        {
            Contract.Requires(ev != null);

            // note that this only works for RuntimeMethodInfo
            MethodInfo add = ev.GetAddMethod(true);

            RuntimeMethodInfo rtAdd = add as RuntimeMethodInfo;

            if (rtAdd != null)
            {
                rtAdd = rtAdd.GetParentDefinition();
                if (rtAdd != null)
                    return rtAdd.DeclaringType.GetEvent(ev.Name);
            }
            return null;
        }

        private static bool InternalIsDefined(EventInfo element, Type attributeType, bool inherit)
        {
            Contract.Requires(element != null);

            // walk up the hierarchy chain
            if (element.IsDefined(attributeType, inherit))
                return true;

            if (inherit)
            {
                AttributeUsageAttribute usage = InternalGetAttributeUsage(attributeType);

                if (!usage.Inherited)
                    return false;

                EventInfo baseEvent = GetParentDefinition(element);

                while (baseEvent != null)
                {
                    if (baseEvent.IsDefined(attributeType, false))
                        return true;
                    baseEvent = GetParentDefinition(baseEvent);
                }
            }

            return false;
        }

        #endregion

        #region ParameterInfo
        private static ParameterInfo GetParentDefinition(ParameterInfo param)
        {
            Contract.Requires(param != null);

            // note that this only works for RuntimeMethodInfo
            RuntimeMethodInfo rtMethod = param.Member as RuntimeMethodInfo;

            if (rtMethod != null)
            {
                rtMethod = rtMethod.GetParentDefinition();

                if (rtMethod != null)
                {
                    // Find the ParameterInfo on this method
                    int position = param.Position;
                    if (position == -1)
                    {
                        return rtMethod.ReturnParameter;
                    }
                    else
                    {
                        ParameterInfo[] parameters = rtMethod.GetParameters();
                        return parameters[position]; // Point to the correct ParameterInfo of the method
                    }
                }
            }
            return null;
        }

        private static Attribute[] InternalParamGetCustomAttributes(ParameterInfo param, Type type, bool inherit)
        {
            Contract.Requires(param != null);

            // For ParameterInfo's we need to make sure that we chain through all the MethodInfo's in the inheritance chain that
            // have this ParameterInfo defined. .We pick up all the CustomAttributes for the starting ParameterInfo. We need to pick up only attributes 
            // that are marked inherited from the remainder of the MethodInfo's in the inheritance chain.
            // For MethodInfo's on an interface we do not do an inheritance walk so the default ParameterInfo attributes are returned.
            // For MethodInfo's on a class we walk up the inheritance chain but do not look at the MethodInfo's on the interfaces that the
            // class inherits from and return the respective ParameterInfo attributes

            List<Type> disAllowMultiple = new List<Type>();
            Object[] objAttr;

            if (type == null)
                type = typeof(Attribute);

            objAttr = param.GetCustomAttributes(type, false);

            for (int i = 0; i < objAttr.Length; i++)
            {
                Type objType = objAttr[i].GetType();
                AttributeUsageAttribute attribUsage = InternalGetAttributeUsage(objType);
                if (attribUsage.AllowMultiple == false)
                    disAllowMultiple.Add(objType);
            }

            // Get all the attributes that have Attribute as the base class
            Attribute[] ret = null;
            if (objAttr.Length == 0)
                ret = CreateAttributeArrayHelper(type, 0);
            else
                ret = (Attribute[])objAttr;

            if (param.Member.DeclaringType == null) // This is an interface so we are done.
                return ret;

            if (!inherit)
                return ret;

            ParameterInfo baseParam = GetParentDefinition(param);

            while (baseParam != null)
            {
                objAttr = baseParam.GetCustomAttributes(type, false);

                int count = 0;
                for (int i = 0; i < objAttr.Length; i++)
                {
                    Type objType = objAttr[i].GetType();
                    AttributeUsageAttribute attribUsage = InternalGetAttributeUsage(objType);

                    if ((attribUsage.Inherited) && (disAllowMultiple.Contains(objType) == false))
                    {
                        if (attribUsage.AllowMultiple == false)
                            disAllowMultiple.Add(objType);
                        count++;
                    }
                    else
                        objAttr[i] = null;
                }

                // Get all the attributes that have Attribute as the base class
                Attribute[] attributes = CreateAttributeArrayHelper(type, count);

                count = 0;
                for (int i = 0; i < objAttr.Length; i++)
                {
                    if (objAttr[i] != null)
                    {
                        attributes[count] = (Attribute)objAttr[i];
                        count++;
                    }
                }

                Attribute[] temp = ret;
                ret = CreateAttributeArrayHelper(type, temp.Length + count);
                Array.Copy(temp, ret, temp.Length);

                int offset = temp.Length;

                for (int i = 0; i < attributes.Length; i++)
                    ret[offset + i] = attributes[i];

                baseParam = GetParentDefinition(baseParam);
            }

            return ret;
        }

        private static bool InternalParamIsDefined(ParameterInfo param, Type type, bool inherit)
        {
            Contract.Requires(param != null);
            Contract.Requires(type != null);

            // For ParameterInfo's we need to make sure that we chain through all the MethodInfo's in the inheritance chain.
            // We pick up all the CustomAttributes for the starting ParameterInfo. We need to pick up only attributes 
            // that are marked inherited from the remainder of the ParameterInfo's in the inheritance chain.
            // For MethodInfo's on an interface we do not do an inheritance walk. For ParameterInfo's on a
            // Class we walk up the inheritance chain but do not look at the MethodInfo's on the interfaces that the class inherits from.

            if (param.IsDefined(type, false))
                return true;

            if (param.Member.DeclaringType == null || !inherit) // This is an interface so we are done.
                return false;

            ParameterInfo baseParam = GetParentDefinition(param);

            while (baseParam != null)
            {
                Object[] objAttr = baseParam.GetCustomAttributes(type, false);

                for (int i = 0; i < objAttr.Length; i++)
                {
                    Type objType = objAttr[i].GetType();
                    AttributeUsageAttribute attribUsage = InternalGetAttributeUsage(objType);

                    if ((objAttr[i] is Attribute) && (attribUsage.Inherited))
                        return true;
                }

                baseParam = GetParentDefinition(baseParam);
            }

            return false;
        }

        #endregion

        #region Utility
        private static void CopyToArrayList(List<Attribute> attributeList, Attribute[] attributes, Dictionary<Type, AttributeUsageAttribute> types)
        {
            for (int i = 0; i < attributes.Length; i++)
            {
                attributeList.Add(attributes[i]);

                Type attrType = attributes[i].GetType();

                if (!types.ContainsKey(attrType))
                    types[attrType] = InternalGetAttributeUsage(attrType);
            }
        }

        private static Type[] GetIndexParameterTypes(PropertyInfo element)
        {
            ParameterInfo[] indexParams = element.GetIndexParameters();

            if (indexParams.Length > 0)
            {
                Type[] indexParamTypes = new Type[indexParams.Length];
                for (int i = 0; i < indexParams.Length; i++)
                {
                    indexParamTypes[i] = indexParams[i].ParameterType;
                }
                return indexParamTypes;
            }

            return Array.Empty<Type>();
        }

        private static void AddAttributesToList(List<Attribute> attributeList, Attribute[] attributes, Dictionary<Type, AttributeUsageAttribute> types)
        {
            for (int i = 0; i < attributes.Length; i++)
            {
                Type attrType = attributes[i].GetType();
                AttributeUsageAttribute usage = null;
                types.TryGetValue(attrType, out usage);

                if (usage == null)
                {
                    // the type has never been seen before if it's inheritable add it to the list
                    usage = InternalGetAttributeUsage(attrType);
                    types[attrType] = usage;

                    if (usage.Inherited)
                        attributeList.Add(attributes[i]);
                }
                else if (usage.Inherited && usage.AllowMultiple)
                {
                    // we saw this type already add it only if it is inheritable and it does allow multiple 
                    attributeList.Add(attributes[i]);
                }
            }
        }

        private static AttributeUsageAttribute InternalGetAttributeUsage(Type type)
        {
            // Check if the custom attributes is Inheritable
            Object[] obj = type.GetCustomAttributes(typeof(AttributeUsageAttribute), false);

            if (obj.Length == 1)
                return (AttributeUsageAttribute)obj[0];

            if (obj.Length == 0)
                return AttributeUsageAttribute.Default;

            throw new FormatException(
                SR.Format(SR.Format_AttributeUsage, type));
        }

        private static Attribute[] CreateAttributeArrayHelper(Type elementType, int elementCount)
        {
            return (Attribute[])Array.UnsafeCreateInstance(elementType, elementCount);
        }
        #endregion

        #endregion

        #region Public Statics

        #region MemberInfo
        public static Attribute[] GetCustomAttributes(MemberInfo element, Type type)
        {
            return GetCustomAttributes(element, type, true);
        }

        public static Attribute[] GetCustomAttributes(MemberInfo element, Type type, bool inherit)
        {
            if (element == null)
                throw new ArgumentNullException(nameof(element));

            if (type == null)
                throw new ArgumentNullException(nameof(type));

            if (!type.IsSubclassOf(typeof(Attribute)) && type != typeof(Attribute))
                throw new ArgumentException(SR.Argument_MustHaveAttributeBaseClass);
            Contract.EndContractBlock();

            switch (element.MemberType)
            {
                case MemberTypes.Property:
                    return InternalGetCustomAttributes((PropertyInfo)element, type, inherit);

                case MemberTypes.Event:
                    return InternalGetCustomAttributes((EventInfo)element, type, inherit);

                default:
                    return element.GetCustomAttributes(type, inherit) as Attribute[];
            }
        }

        public static Attribute[] GetCustomAttributes(MemberInfo element)
        {
            return GetCustomAttributes(element, true);
        }

        public static Attribute[] GetCustomAttributes(MemberInfo element, bool inherit)
        {
            if (element == null)
                throw new ArgumentNullException(nameof(element));
            Contract.EndContractBlock();

            switch (element.MemberType)
            {
                case MemberTypes.Property:
                    return InternalGetCustomAttributes((PropertyInfo)element, typeof(Attribute), inherit);

                case MemberTypes.Event:
                    return InternalGetCustomAttributes((EventInfo)element, typeof(Attribute), inherit);

                default:
                    return element.GetCustomAttributes(typeof(Attribute), inherit) as Attribute[];
            }
        }

        public static bool IsDefined(MemberInfo element, Type attributeType)
        {
            return IsDefined(element, attributeType, true);
        }

        public static bool IsDefined(MemberInfo element, Type attributeType, bool inherit)
        {
            // Returns true if a custom attribute subclass of attributeType class/interface with inheritance walk
            if (element == null)
                throw new ArgumentNullException(nameof(element));

            if (attributeType == null)
                throw new ArgumentNullException(nameof(attributeType));

            if (!attributeType.IsSubclassOf(typeof(Attribute)) && attributeType != typeof(Attribute))
                throw new ArgumentException(SR.Argument_MustHaveAttributeBaseClass);
            Contract.EndContractBlock();

            switch (element.MemberType)
            {
                case MemberTypes.Property:
                    return InternalIsDefined((PropertyInfo)element, attributeType, inherit);

                case MemberTypes.Event:
                    return InternalIsDefined((EventInfo)element, attributeType, inherit);

                default:
                    return element.IsDefined(attributeType, inherit);
            }
        }

        public static Attribute GetCustomAttribute(MemberInfo element, Type attributeType)
        {
            return GetCustomAttribute(element, attributeType, true);
        }

        public static Attribute GetCustomAttribute(MemberInfo element, Type attributeType, bool inherit)
        {
            Attribute[] attrib = GetCustomAttributes(element, attributeType, inherit);

            if (attrib == null || attrib.Length == 0)
                return null;

            if (attrib.Length == 1)
                return attrib[0];

            throw new AmbiguousMatchException(SR.RFLCT_AmbigCust);
        }

        #endregion

        #region ParameterInfo
        public static Attribute[] GetCustomAttributes(ParameterInfo element)
        {
            return GetCustomAttributes(element, true);
        }

        public static Attribute[] GetCustomAttributes(ParameterInfo element, Type attributeType)
        {
            return (Attribute[])GetCustomAttributes(element, attributeType, true);
        }

        public static Attribute[] GetCustomAttributes(ParameterInfo element, Type attributeType, bool inherit)
        {
            if (element == null)
                throw new ArgumentNullException(nameof(element));

            if (attributeType == null)
                throw new ArgumentNullException(nameof(attributeType));

            if (!attributeType.IsSubclassOf(typeof(Attribute)) && attributeType != typeof(Attribute))
                throw new ArgumentException(SR.Argument_MustHaveAttributeBaseClass);

            if (element.Member == null)
                throw new ArgumentException(SR.Argument_InvalidParameterInfo, nameof(element));

            Contract.EndContractBlock();

            MemberInfo member = element.Member;
            if (member.MemberType == MemberTypes.Method && inherit)
                return InternalParamGetCustomAttributes(element, attributeType, inherit) as Attribute[];

            return element.GetCustomAttributes(attributeType, inherit) as Attribute[];
        }

        public static Attribute[] GetCustomAttributes(ParameterInfo element, bool inherit)
        {
            if (element == null)
                throw new ArgumentNullException(nameof(element));

            if (element.Member == null)
                throw new ArgumentException(SR.Argument_InvalidParameterInfo, nameof(element));

            Contract.EndContractBlock();

            MemberInfo member = element.Member;
            if (member.MemberType == MemberTypes.Method && inherit)
                return InternalParamGetCustomAttributes(element, null, inherit) as Attribute[];

            return element.GetCustomAttributes(typeof(Attribute), inherit) as Attribute[];
        }

        public static bool IsDefined(ParameterInfo element, Type attributeType)
        {
            return IsDefined(element, attributeType, true);
        }

        public static bool IsDefined(ParameterInfo element, Type attributeType, bool inherit)
        {
            // Returns true is a custom attribute subclass of attributeType class/interface with inheritance walk
            if (element == null)
                throw new ArgumentNullException(nameof(element));

            if (attributeType == null)
                throw new ArgumentNullException(nameof(attributeType));

            if (!attributeType.IsSubclassOf(typeof(Attribute)) && attributeType != typeof(Attribute))
                throw new ArgumentException(SR.Argument_MustHaveAttributeBaseClass);
            Contract.EndContractBlock();

            MemberInfo member = element.Member;

            switch (member.MemberType)
            {
                case MemberTypes.Method: // We need to climb up the member hierarchy            
                    return InternalParamIsDefined(element, attributeType, inherit);

                case MemberTypes.Constructor:
                    return element.IsDefined(attributeType, false);

                case MemberTypes.Property:
                    return element.IsDefined(attributeType, false);

                default:
                    Debug.Assert(false, "Invalid type for ParameterInfo member in Attribute class");
                    throw new ArgumentException(SR.Argument_InvalidParamInfo);
            }
        }

        public static Attribute GetCustomAttribute(ParameterInfo element, Type attributeType)
        {
            return GetCustomAttribute(element, attributeType, true);
        }

        public static Attribute GetCustomAttribute(ParameterInfo element, Type attributeType, bool inherit)
        {
            // Returns an Attribute of base class/inteface attributeType on the ParameterInfo or null if none exists.
            // throws an AmbiguousMatchException if there are more than one defined.
            Attribute[] attrib = GetCustomAttributes(element, attributeType, inherit);

            if (attrib == null || attrib.Length == 0)
                return null;

            if (attrib.Length == 0)
                return null;

            if (attrib.Length == 1)
                return attrib[0];

            throw new AmbiguousMatchException(SR.RFLCT_AmbigCust);
        }

        #endregion

        #region Module
        public static Attribute[] GetCustomAttributes(Module element, Type attributeType)
        {
            return GetCustomAttributes(element, attributeType, true);
        }

        public static Attribute[] GetCustomAttributes(Module element)
        {
            return GetCustomAttributes(element, true);
        }

        public static Attribute[] GetCustomAttributes(Module element, bool inherit)
        {
            if (element == null)
                throw new ArgumentNullException(nameof(element));
            Contract.EndContractBlock();

            return (Attribute[])element.GetCustomAttributes(typeof(Attribute), inherit);
        }

        public static Attribute[] GetCustomAttributes(Module element, Type attributeType, bool inherit)
        {
            if (element == null)
                throw new ArgumentNullException(nameof(element));

            if (attributeType == null)
                throw new ArgumentNullException(nameof(attributeType));

            if (!attributeType.IsSubclassOf(typeof(Attribute)) && attributeType != typeof(Attribute))
                throw new ArgumentException(SR.Argument_MustHaveAttributeBaseClass);
            Contract.EndContractBlock();

            return (Attribute[])element.GetCustomAttributes(attributeType, inherit);
        }

        public static bool IsDefined(Module element, Type attributeType)
        {
            return IsDefined(element, attributeType, false);
        }

        public static bool IsDefined(Module element, Type attributeType, bool inherit)
        {
            // Returns true is a custom attribute subclass of attributeType class/interface with no inheritance walk
            if (element == null)
                throw new ArgumentNullException(nameof(element));

            if (attributeType == null)
                throw new ArgumentNullException(nameof(attributeType));

            if (!attributeType.IsSubclassOf(typeof(Attribute)) && attributeType != typeof(Attribute))
                throw new ArgumentException(SR.Argument_MustHaveAttributeBaseClass);
            Contract.EndContractBlock();

            return element.IsDefined(attributeType, false);
        }

        public static Attribute GetCustomAttribute(Module element, Type attributeType)
        {
            return GetCustomAttribute(element, attributeType, true);
        }

        public static Attribute GetCustomAttribute(Module element, Type attributeType, bool inherit)
        {
            // Returns an Attribute of base class/inteface attributeType on the Module or null if none exists.
            // throws an AmbiguousMatchException if there are more than one defined.
            Attribute[] attrib = GetCustomAttributes(element, attributeType, inherit);

            if (attrib == null || attrib.Length == 0)
                return null;

            if (attrib.Length == 1)
                return attrib[0];

            throw new AmbiguousMatchException(SR.RFLCT_AmbigCust);
        }

        #endregion

        #region Assembly
        public static Attribute[] GetCustomAttributes(Assembly element, Type attributeType)
        {
            return GetCustomAttributes(element, attributeType, true);
        }

        public static Attribute[] GetCustomAttributes(Assembly element, Type attributeType, bool inherit)
        {
            if (element == null)
                throw new ArgumentNullException(nameof(element));

            if (attributeType == null)
                throw new ArgumentNullException(nameof(attributeType));

            if (!attributeType.IsSubclassOf(typeof(Attribute)) && attributeType != typeof(Attribute))
                throw new ArgumentException(SR.Argument_MustHaveAttributeBaseClass);
            Contract.EndContractBlock();

            return (Attribute[])element.GetCustomAttributes(attributeType, inherit);
        }

        public static Attribute[] GetCustomAttributes(Assembly element)
        {
            return GetCustomAttributes(element, true);
        }

        public static Attribute[] GetCustomAttributes(Assembly element, bool inherit)
        {
            if (element == null)
                throw new ArgumentNullException(nameof(element));
            Contract.EndContractBlock();

            return (Attribute[])element.GetCustomAttributes(typeof(Attribute), inherit);
        }

        public static bool IsDefined(Assembly element, Type attributeType)
        {
            return IsDefined(element, attributeType, true);
        }

        public static bool IsDefined(Assembly element, Type attributeType, bool inherit)
        {
            // Returns true is a custom attribute subclass of attributeType class/interface with no inheritance walk
            if (element == null)
                throw new ArgumentNullException(nameof(element));

            if (attributeType == null)
                throw new ArgumentNullException(nameof(attributeType));

            if (!attributeType.IsSubclassOf(typeof(Attribute)) && attributeType != typeof(Attribute))
                throw new ArgumentException(SR.Argument_MustHaveAttributeBaseClass);
            Contract.EndContractBlock();

            return element.IsDefined(attributeType, false);
        }

        public static Attribute GetCustomAttribute(Assembly element, Type attributeType)
        {
            return GetCustomAttribute(element, attributeType, true);
        }

        public static Attribute GetCustomAttribute(Assembly element, Type attributeType, bool inherit)
        {
            // Returns an Attribute of base class/inteface attributeType on the Assembly or null if none exists.
            // throws an AmbiguousMatchException if there are more than one defined.
            Attribute[] attrib = GetCustomAttributes(element, attributeType, inherit);

            if (attrib == null || attrib.Length == 0)
                return null;

            if (attrib.Length == 1)
                return attrib[0];

            throw new AmbiguousMatchException(SR.RFLCT_AmbigCust);
        }

        #endregion

        #endregion

        #region Constructor
        protected Attribute() { }
        #endregion

        #region Object Overrides
        public override bool Equals(Object obj)
        {
            if (obj == null)
                return false;

            Type thisType = this.GetType();
            Type thatType = obj.GetType();

            if (thatType != thisType)
                return false;

            Object thisObj = this;
            Object thisResult, thatResult;

            while (thisType != typeof(Attribute))
            {
                FieldInfo[] thisFields = thisType.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly);

                for (int i = 0; i < thisFields.Length; i++)
                {
                    // Visibility check and consistency check are not necessary.
                    thisResult = ((RtFieldInfo)thisFields[i]).UnsafeGetValue(thisObj);
                    thatResult = ((RtFieldInfo)thisFields[i]).UnsafeGetValue(obj);

                    if (!AreFieldValuesEqual(thisResult, thatResult))
                    {
                        return false;
                    }
                }
                thisType = thisType.BaseType;
            }

            return true;
        }

        // Compares values of custom-attribute fields.    
        private static bool AreFieldValuesEqual(Object thisValue, Object thatValue)
        {
            if (thisValue == null && thatValue == null)
                return true;
            if (thisValue == null || thatValue == null)
                return false;

            if (thisValue.GetType().IsArray)
            {
                // Ensure both are arrays of the same type.
                if (!thisValue.GetType().Equals(thatValue.GetType()))
                {
                    return false;
                }

                Array thisValueArray = thisValue as Array;
                Array thatValueArray = thatValue as Array;
                if (thisValueArray.Length != thatValueArray.Length)
                {
                    return false;
                }

                // Attributes can only contain single-dimension arrays, so we don't need to worry about 
                // multidimensional arrays.
                Debug.Assert(thisValueArray.Rank == 1 && thatValueArray.Rank == 1);
                for (int j = 0; j < thisValueArray.Length; j++)
                {
                    if (!AreFieldValuesEqual(thisValueArray.GetValue(j), thatValueArray.GetValue(j)))
                    {
                        return false;
                    }
                }
            }
            else
            {
                // An object of type Attribute will cause a stack overflow. 
                // However, this should never happen because custom attributes cannot contain values other than
                // constants, single-dimensional arrays and typeof expressions.
                Debug.Assert(!(thisValue is Attribute));
                if (!thisValue.Equals(thatValue))
                    return false;
            }

            return true;
        }

        public override int GetHashCode()
        {
            Type type = GetType();

            while (type != typeof(Attribute))
            {
                FieldInfo[] fields = type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly);
                Object vThis = null;

                for (int i = 0; i < fields.Length; i++)
                {
                    // Visibility check and consistency check are not necessary.
                    Object fieldValue = ((RtFieldInfo)fields[i]).UnsafeGetValue(this);

                    // The hashcode of an array ignores the contents of the array, so it can produce 
                    // different hashcodes for arrays with the same contents.
                    // Since we do deep comparisons of arrays in Equals(), this means Equals and GetHashCode will
                    // be inconsistent for arrays. Therefore, we ignore hashes of arrays.
                    if (fieldValue != null && !fieldValue.GetType().IsArray)
                        vThis = fieldValue;

                    if (vThis != null)
                        break;
                }

                if (vThis != null)
                    return vThis.GetHashCode();

                type = type.BaseType;
            }

            return type.GetHashCode();
        }
        #endregion

        #region Public Virtual Members
        public virtual Object TypeId { get { return GetType(); } }

        public virtual bool Match(Object obj) { return Equals(obj); }
        #endregion

        #region Public Members
        public virtual bool IsDefaultAttribute() { return false; }
        #endregion
    }
}