I've been using the DefaultValue attribute in a code generator which writes a C# class definition from a schema.
I'm stuck where a property in the schema is an array of strings.
I'd like to write something like this in my C#:
[DefaultValue(typeof(string[]), ["a","b"])]
public string[] Names{get;set;}
but that won't compile.
Is there any way I can successfully declare the default value attribute for a string array?
You could try
[DefaultValue(new string[] { "a", "b" })]
As you want to pass a new string array, you have to instantiate it - that's done by new string[]
. C# allows an initialization list with the initial contents of the array to follow in braces, i.e. { "a", "b" }
.
EDIT: As correctly pointed out by Cory-G, you may want to make sure your actual instances do not receive the very array instance stored in the DefaultValue
attribute. Otherwise, changes to that instance might influence default values across your application.
Instead, you could use your property's setter to copy the assigned array.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With