2
3

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#のArrayもList<T>と同じ様に扱いたい

Last updated at Posted at 2021-03-01

はじめに

最近はコレクションを処理するのに、LINQばかり使っているので、Arrayのメソッドを呼び出すことはあまりないのだけれど、稀にArrayのメソッドを呼び出したい時があります。

でも、

var items = new[] { 5, 3, 7, 9, 1, 4 };
Array.ForEach(items, Console.WriteLine);

て書くのはなんかイヤです。やっぱり、

var items = new[] { 5, 3, 7, 9, 1, 4 };
items.ForEach(Console.WriteLine);

って書きたいです。

拡張メソッドを定義しよう

そんな時は拡張メソッドの出番です。以下の様な拡張メソッドを定義することで、ArrayのメソッドもList<T>と同じ様な感覚でコードを書くことができます。

public static class ArrayExtensions
{
	public static void ForEach<T>(this T[] array, Action<T> action)
	{
		Array.ForEach(array, action);
	}

	public static void Sort<T>(this T[] array) where T : IComparable<T>
	{
		Array.Sort(array);
	}
}

ArrayExtensionsが定義されている名前空間をusingすれば、以下の様な記述が可能になります。

var items = new[] { 5, 3, 7, 9, 1, 4 };
items.Sort();
items.ForEach(Console.WriteLine);

結果は以下の通り。

1
3
4
5
7
9

IndexOfやFindAllなどのメソッドも同様に拡張メソッドにすれば使い勝手もよくなります。

おわりに

まあ、LINQあるのでこういった拡張メソッドを書く必要性もあまり無いんですけどね。

昔書いたブログ記事を読み直していて、拡張メソッドで遊んでいたことを懐かしく思い出したので、こんな記事を書いてみました。

2
3
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
2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?