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.
Old post I know but there is a work-around. I had a similar problem when using Reflection and Custom Attributes. I changed the property to update the set value if it was Null like below.
was changed to:
So now, even if you assign Null or fail to assign a value it will work but you may need to update your logic elsewhere if you are expecting to skip the attribute if it is set as Null.
Also in my case this was when handling an array of int[] not object[].