Reputation:
I saw this answer from this link Adding parameters to custom attributes of how is to add parameters on Custom Attribute
class MyCustomAttribute : Attribute {
public int[] Values { get; set; }
public MyCustomAttribute(params int[] values) {
this.Values = values;
}
}
[MyCustomAttribute(3, 4, 5)]
class MyClass { }
Now I am wondering if can't it be write like this?
class MyCustomAttribute : Attribute {
private int[] _values;
public MyCustomAttribute(params int[] values) {
_values = values;
}
}
[MyCustomAttribute(3, 4, 5)]
class MyClass { }
I changed the property Values into a variable _values. I also made it private and it works fine when I tried it.
Can someone enlighten me why the accepted answer is valid?
Upvotes: 14
Views: 55703
Reputation: 5539
There are differences, and it is all about reflection
.
Main among them is the fluency that we get - we could either use the constructor or the Values
property.
public class MyCustomAttribute : Attribute
{
public int[] Values { get; set; } = new int[] { 1, 2, 3 };
public MyCustomAttribute(params int[] values)
{
this.Values = values;
}
}
[MyCustom(1, 2, 3)]
class MyClass
{
}
[MyCustom(Values = new int[] { 1, 2, 3})]
public class MyAnotherClass
{
}
Another factor is reflection
to get the property; With the Values
field being public
, we could use the below to get the details but not with private
:
var data = typeof(MyCustomAttribute).GetProperty("Values");
Upvotes: 6
Reputation: 15445
For [MyCustomAttribute(3, 4, 5)]
the parameter list is unnamed, so the the constructor of MyCustomAttribute
is used.
Therefore it does not matter, if there is a public Values
properties.
In your first code sample it is acceptable to use [MyCustomAttribute(3, 4, 5)]
and [MyCustom(Values = new[] {3, 4, 5})]
.
The second code sample "only" accepts [MyCustomAttribute(3, 4, 5)]
.
Upvotes: 5
Reputation: 3072
The accepted answer uses the public property instead of a private field. The benefit of public property is you can omit the constructor and supply the values of the properties in the default constructor.
I change your first code, the one with public property, to something like this.
class MyCustomAttribute : Attribute {
public int[] Values { get; set; }
}
[MyCustomAttribute(Values = new int[] { 3, 4, 5 })]
class MyClass { }
Upvotes: 16