C# switch case

switch case C# 入門

switch case  int

switch caseは値に対して分岐します。

switch (式)
{
case 値:
処理
break;
}

breakはswitch文から抜けます。

default:はそれ以外の時です。

サンプルソース
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApplication4
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)
{

int a = 1;

switch (a)
{
case 1:
Console.WriteLine(“1”);

break;

default:

break;

}

}

}
}

実行結果は
1が
表示されます。

switch case  string 文字列

string型の場合は値に””で書きます。

サンプルソース

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApplication4
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)
{

string str= “hellworld”;

switch (str)
{
case “hellworld”:
Console.WriteLine(“hellworldにようこそ”);

break;
}
}

}
}

実行結果は

hellworldにようこそ

switch case  char 文字

文字の場合は値に”で書きます。

サンプルソース

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApplication4
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)
{

char b =’c’
switch b)
{
case ‘c’:
Console.WriteLine(c);

break;

default:
break;
}
}

}
}

実行結果は

cになります。

switch case  時間

時間で分岐したい場合。

サンプルソース

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApplication4
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)
{

DateTime date = DateTime.Now;
int hour = date.Hour;

switch (hour)
{
case 1:
Console.WriteLine(“1”);

break;

default:
break;
}
}

private void Form1_Load(object sender, EventArgs e)
{

}
}
}

実行結果は

今が1地なら1を表示されます。

時間はint型を経由してつかえばいいですね。

シェアする

  • このエントリーをはてなブックマークに追加

フォローする

Translate »