0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【C#】.NET FrameworkではArray.Fillを使えない

Last updated at Posted at 2022-04-18

ドキュメントちゃんと見ればわかるけど意外と気づかなかったのでメモ程度に


まったく同じ値を、指定した個数持った配列を作って、最後String.Joinでパイプ区切りにしたかった

JavaScriptでfillメソッドあるのを思い出したからC#にもあるのでは?と思って調べた

理想はこんな感じ(書き方あってるかな、、)

int num = 3;
string str = "text";
string[] arr = new string[num];
Array.Fill(arr, str);
Console.WriteLine(String.Join("|", arr));
// output: text|text|text

使ってみたけどエラーが、、
もう一度ドキュメント確認してみたら.NET FrameworkはArray.Fillは対応していなかった

結局for文で回してList.Addをすることにしました

int num = 3;
string str = "text";
List<string> list = new List<string>();
for (var i = 0; i < num; i++)
{
  list.Add(str);
}
Console.WriteLine(String.Join("|", list));
// output: text|text|text
0
0
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?