I've been fighting this problem for hours and I could not find anything related on SO (or google for that matter).
Here's my problem: I have a custom attribute that contains an object array property.
[System.AttributeUsage(System.AttributeTargets.Property, AllowMultiple = false)]
public class Property : System.Attribute
{
public object[] Parameters { get; set; }
public JsonProperty(object[] prms = null)
{
Parameters = prms;
}
}
And then I use the following code to read it from the properties:
var customProperties = (Property[])currentProperty.GetCustomAttributes(typeof(Property), false);
This all works fine for the following:
[Property(Parameters = new object[]{}]
<...property...>
However, if I set it to null ([Property(Parameters = null])
, I get this error:
System.Reflection.CustomAttributeFormatException:
'Parameters' property specified was not found.
Which is absurd, because the property is defined inside my custom attribute. I really don't get it.
So my question is: what is going on?
--Edit
If I change the type of the property from object[] to object, assigning null works just fine.
--Edit to add the code
Attribute:
[System.AttributeUsage(System.AttributeTargets.Property, AllowMultiple = false)]
public class JsonProperty : System.Attribute
{
public object[] Parameters { get; set; }
public JsonProperty(object[] prms = null)
{
Parameters = prms;
}
}
Class:
public class MyClass
{
[JsonProperty(Parameters = null)]
public DateTime Start { get; set; }
}
Method:
public string getAttributes()
{
Type t = MyClass.GetType();
// Get only public properties and that have been set.
var properties = t.GetProperties(BindingFlags.Public | BindingFlags.Instance)
.Where(prop => prop.GetValue(this, null) != null);
foreach (var prop in properties)
{
//The error occur on the next line.
var jsonProperties =
(JsonProperty[])prop.GetCustomAttributes(typeof(JsonProperty), false);
--If you didn't understand, try reading this:
I asked the question there too.
I had the same error with
System.Runtime.Serialization.OptionalFieldAttribute
. To reproduce it it's enough to add a field, mark it with attribute and later callFieldInfo.GetCustomAttributes()
.The good question is why! The answer as I see we can get from code of
GetCustomAttributes()
, where there is atry{}catch{}
, which catches all errors and throwsCustomAttributeFormatException
, so I think the error in my case comes from setter ofOptionalFieldAttribute
:The message of exception is definitely not helpful, because it gives not a root cause!