Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I declare a DefaultValue attribute whose value is an array of strings?

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?

like image 578
Michael Bishop Avatar asked Sep 18 '12 14:09

Michael Bishop


1 Answers

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.

like image 51
O. R. Mapper Avatar answered Sep 24 '22 17:09

O. R. Mapper