C
C#12mo ago
nathanAjacobs

Is there any difference between named arguments and default constructor arguments for an attribute?

Is there any difference between these attributes? Is one better to use than the other?
[AttributeUsage(AttributeTargets.Class)]
public class CustomAttribute : System.Attribute
{
public string Name { get; }

public CustomAttribute(string name = "")
{
Name = name;
}
}

[AttributeUsage(AttributeTargets.Class)]
public class CustomNonDefaultAttribute : System.Attribute
{
public string Name { get; set; } = "";
}

[Custom(name: "sdfsd")]
[CustomNonDefault(Name = "sdfsd")]
public class MyClass
{
}
[AttributeUsage(AttributeTargets.Class)]
public class CustomAttribute : System.Attribute
{
public string Name { get; }

public CustomAttribute(string name = "")
{
Name = name;
}
}

[AttributeUsage(AttributeTargets.Class)]
public class CustomNonDefaultAttribute : System.Attribute
{
public string Name { get; set; } = "";
}

[Custom(name: "sdfsd")]
[CustomNonDefault(Name = "sdfsd")]
public class MyClass
{
}
2 Replies
333fred
333fred12mo ago
The BCL prefers properties, because adding a new default ctor parameter can be a breaking change if you don't leave the old constructor there
nathanAjacobs
nathanAjacobsOP12mo ago
Thanks for that insight!
Want results from more Discord servers?
Add your server