動くコード図鑑技術記事現場の渡り方キャリア論すべての記事About

動くコード図鑑

$ ls -1 /library | wc -l → 619

触って動く、検証済みの正解集。

公開記事から抽出した全コードブロックを 1 つずつページ化。 ▶ ボタンで 実行ログを再生し、 さも今動いてるかのように出力を流す。

この図鑑の使い方

言語で絞る

C# / SQL / TypeScript / PowerShell / Bash でフィルタ。

▶ で実行

事前収録の出力を 1 行ずつ再生。 ぱっと結果が見える。

記事と接続

各 snippet は出典記事へのリンク付き。 文脈ごと読める。

絞り込み

snippet 一覧

473
C#
    public class Plane : IVehicle
    {
        public string MoveSound => "ごぉーーーーーー";
    }

Interfaceの準備

【C#】Interfaceを継承しているかを判断しついでにコンバートしてみる未収録#4daba4d61b7d
C#
        static void Main(string[] args)
        {
            var plane = new Plane();
            var car = plane as ICar;

▶ 実行可

Interfaceを継承しているかの判断

【C#】Interfaceを継承しているかを判断しついでにコンバートしてみる#410a80545d69
C#
        static void Main(string[] args)
        {
            IVehicle plane = new Plane();
            var car = plane as ICar;

▶ 実行可

InterfaceからInterfaceの継承チェックもできる。

【C#】Interfaceを継承しているかを判断しついでにコンバートしてみる#798be77e4d3a
C#
        static void Main(string[] args)
        {
            IVehicle subaru = new Subaru();
            var car = subaru as ICar;

▶ 実行可

InterfaceからInterfaceの継承チェックもできる。

【C#】Interfaceを継承しているかを判断しついでにコンバートしてみる#d2480278713e
C#
        static void Main(string[] args)
        {
            IVehicle subaru = new Subaru();

        if (subaru is ICar car)
▶ 実行可

Interfaceを継承していたらコンバートする

【C#】Interfaceを継承しているかを判断しついでにコンバートしてみる#2ec7ce5942d1
C#
        static void Main(string[] args)
        {
            IVehicle plane = new Plane();

        if (plane is ICar car)
▶ 実行可

Interfaceを継承していたらコンバートする

【C#】Interfaceを継承しているかを判断しついでにコンバートしてみる#1e6b84fd6356
C#
// ✅定石1:配列T[] の基本
int[] daysInMonth = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
string[] weekDays = new string[7] { "月", "火", "水", "木", "金", "土", "日" };

//インデックスアクセス

定石1:配列T[] —固定長・最速だがAPIでは出番が絞られる

C# のコレクション選び — 配列 / List / IEnumerable / IList の使い分け完全ガイド未収録#30be80acb5d1
C#
// ✅定石2: List<T>の基本
var customers = new List<CustomerVm>();

//追加
customers.Add(new CustomerVm { Id = 1, Name = "サンプル商事" });

定石2: List<T> —可変長・最も多用される実装型

C# のコレクション選び — 配列 / List / IEnumerable / IList の使い分け完全ガイド未収録#a559247150e8
C#
// ✅定石3: IEnumerable<T>と遅延評価
public IEnumerable<CustomerVm> GetActiveCustomers()
{
    return _db.Customers
        .Where(c => c.Status == "active")
▶ 実行可

定石3: IEnumerable<T> —遅延評価・LINQの基本型

C# のコレクション選び — 配列 / List / IEnumerable / IList の使い分け完全ガイド#492870f19ead
C#
// ✅定石4: IList<T>をメソッド引数で受ける
public void ProcessCustomers(IList<CustomerVm> customers)
{
    //インデックスアクセス
    var first = customers[0];

定石4: IList<T> —メソッド引数の汎用型

C# のコレクション選び — 配列 / List / IEnumerable / IList の使い分け完全ガイド未収録#3ab6caaff422
C#
// ✅定石5:共変(covariance)の例
class Animal { }
class Dog : Animal { }

// ✅ IEnumerable<Dog>はIEnumerable<Animal>に代入可能(共変・out T)

定石5:共変・反変の罠— IEnumerable<T>は共変・IList<T>は不変

C# のコレクション選び — 配列 / List / IEnumerable / IList の使い分け完全ガイド未収録#9af670d7acd0
C#
    public partial class Form2 : Form
    {
        private SqlConnection SqlCon;
        private SqlDataAdapter adapter;
        private SqlCommandBuilder commandBuilder;    public Form2()

コードの全貌

【C#】DataAdapterを使ってFillとUpdateしてみる未収録#226a24b364fd
C#
    public partial class Form2 : Form
    {
        private SqlConnection SqlCon;
        private SqlDataAdapter adapter;
        private SqlCommandBuilder commandBuilder;

Formロード時にインスタンスを生成

【C#】DataAdapterを使ってFillとUpdateしてみる未収録#4ffccc610b90
C#
        private void SqlSettingInitialize()
        {
            var sqlConStrBuilder = new SqlConnectionStringBuilder();
            sqlConStrBuilder.InitialCatalog = @"testDb";
            sqlConStrBuilder.DataSource = @"DESKTOP-B9V2BO1";

Formロード時にインスタンスを生成

【C#】DataAdapterを使ってFillとUpdateしてみる未収録#7323eec088af
C#
        private void button1_Click(object sender, EventArgs e)
        {
            var dt = new DataTable();
            SqlCon.Open();
            adapter.Fill(dt);

Fill

【C#】DataAdapterを使ってFillとUpdateしてみる未収録#312e2e904dc3
C#
        private void button2_Click(object sender, EventArgs e)
        {
            var updateDt = (DataTable) dataGridView1.DataSource;
            SqlCon.Open();
            adapter.Update(updateDt);

Update

【C#】DataAdapterを使ってFillとUpdateしてみる未収録#bab91fe6652b
C#
// NGパターン:null をそのまま渡してる
var p = new SqlParameter("@bikou", SqlDbType.NVarChar);
p.Value = textBoxBikou.Text == "" ? null : textBoxBikou.Text;  // ← ここで爆発の種を仕込む
cmd.Parameters.Add(p);

パターン1: SqlParameterにC#のnullをそのまま渡している

C# DataAdapter.Update() で DBNull 例外が出た時の最短対処未収録#58ea87804b60
C#
public static class DbNullExtensions
{
    /// <summary>null なら DBNull.Value、そうでなければ自身を返す</summary>
    public static object ToDbValue(this object value)
    {

対処1: nullをDBNull.Valueに変換する拡張メソッドを作る

C# DataAdapter.Update() で DBNull 例外が出た時の最短対処未収録#1f6439a1164b
C#
var p = new SqlParameter("@bikou", SqlDbType.NVarChar);
p.Value = (textBoxBikou.Text == "" ? null : textBoxBikou.Text).ToDbValue();
cmd.Parameters.Add(p);

対処1: nullをDBNull.Valueに変換する拡張メソッドを作る

C# DataAdapter.Update() で DBNull 例外が出た時の最短対処未収録#4fa00bdedb04
C#
// 値を入れる前に DBNull.Value に揃える
row["bikou"] = string.IsNullOrEmpty(input)
    ? (object)DBNull.Value
    : input;

対処2: DataTableに書き戻す時もDBNull.Valueで揃える

C# DataAdapter.Update() で DBNull 例外が出た時の最短対処未収録#b388f0f8c525
C#
string bikou = row["bikou"] is DBNull
    ? null
    : (string)row["bikou"];

対処3:取得時はis DBNullでガードしてから受ける

C# DataAdapter.Update() で DBNull 例外が出た時の最短対処未収録#6bc81cb11236
C#
public static T AsOrDefault<T>(this object value) where T : class
{
    return value is DBNull ? null : value as T;
}

対処3:取得時はis DBNullでガードしてから受ける

C# DataAdapter.Update() で DBNull 例外が出た時の最短対処未収録#c3676af36354
C#
public static T? AsOrNull<T>(this object value) where T : struct
{
    return value is DBNull ? (T?)null : (T)value;
}

値型(int / DateTime)にはasが使えない

C# DataAdapter.Update() で DBNull 例外が出た時の最短対処未収録#56e4fca462e0
C#
// 動くと思いきや微妙に怪しい書き方
int? amount = null;
var p = new SqlParameter("@amount", SqlDbType.Int);
p.Value = amount;  // ← null が DBNull.Value に化けてくれない

Nullable<T>をSqlParameterに渡す時の暗黙変換

C# DataAdapter.Update() で DBNull 例外が出た時の最短対処未収録#5982ba02a017
C#
// 先に列を用意(非バインド)
grid.Columns.Add("Id", "ID");
grid.Columns.Add("Name", "名前");

// 末尾に1行追加(値をそのまま渡す)

パターン①: 非バインド時 — Rows.Add / Rows.Insert

C# DataGridView 行追加の3パターン — Rows.Add / DataSource バインド / BindingList の使い分け未収録#91b772042db9
C#
// DataSource にバインド済みの DataTable を取り出して足す
var dt = (DataTable)grid.DataSource;
dt.Rows.Add(3, "高橋"); // grid に自動で反映される

// DataRow を作って詰めてから Add でもOK

パターン②: DataTable バインド時 — ソース側に足す

C# DataGridView 行追加の3パターン — Rows.Add / DataSource バインド / BindingList の使い分け未収録#5c0d2c8be188
C#
public class Employee
{
    public int Id { get; set; }
    public string Name { get; set; }
}

パターン③: BindingList / BindingSource 経由

C# DataGridView 行追加の3パターン — Rows.Add / DataSource バインド / BindingList の使い分け未収録#9954c7301854
C#
var dt = new DataTable();
dt.Columns.Add("Id", typeof(int));
dt.Columns.Add("Name", typeof(string));

var grid = new DataGridView();

ハマり①: DataSource 設定済みで grid.Rows.Add → InvalidOperationException

C# DataGridView 行追加の3パターン — Rows.Add / DataSource バインド / BindingList の使い分け未収録#967f8e84addb
C#
// AllowUserToAddRows = true(既定)のまま件数を数えると…
int count = grid.Rows.Count; // データ3行でも「4」が返る(+新規入力行)

// データ行だけ数えたい時は IsNewRow を除外する
int real = grid.Rows.Cast<DataGridViewRow>().Count(r => !r.IsNewRow);

ハマり②: AllowUserToAddRows の新規入力行で件数が1ズレる

C# DataGridView 行追加の3パターン — Rows.Add / DataSource バインド / BindingList の使い分け未収録#84071369596f
C#
// NGパターン:AutoGenerateColumns=true のまま差し替える
dgv.DataSource = dt1;  // 列が3個(ID/名前/金額)追加される
dgv.DataSource = dt2;  // 列がさらに3個(ID/コード/数量)追加される ← 重複や増殖

パターン1: AutoGenerateColumnsがtrueのまま差し替え

C# DataGridView の DataSource を後から変更する全パターン未収録#688465b5fdca