is演算子を用いると、変数があるデータ型(もしくはそれに対応する.NET Frameworkのクラスのインスタンス)であること
あるいはあるインタフェースを実装しているクラスのインスタンスであることを確認することができます。
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main()
{
string str = "文字列";
if(str is string)
{
Console.WriteLine("str is string.\n");
}
if(str is IComparable)
{
Console.WriteLine("{0} implements IComparable interface.",
str.GetType().ToString());
string str2 = "aiueo";
Console.WriteLine("{0} {1} {2}.\n",
str, str.CompareTo(str2) > 0 ? ">" : "<", str2);
}
int[] myArray = {6, 2, 8, 4, 1};
if(myArray is ICloneable)
{
Console.WriteLine("{0} implements ICloneable interface.\n",
myArray.GetType().ToString());
int[] yourArray = (int[])myArray.Clone();
for(int i=0; i < yourArray.Length; i++)
{
Console.WriteLine("yourArray[{0}]:{1}", i, yourArray[i]);
}
}
}
}
}
上のプログラムを実行すると以下のような結果となります。
str is string.
System.String implements IComparable interface.
文字列 > aiueo.
System.Int32[] implements ICloneable interface.
yourArray[0]:6
yourArray[1]:2
yourArray[2]:8
yourArray[3]:4
yourArray[4]:1