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

ヘルパ2: MidのC#実装

出典: VB.net の Right / Mid / Left を C# に翻訳する完全早見表最短対処:C#用のヘルパメソッド3点(コピペで動く) / ヘルパ2: MidのC#実装

ヘルパ2: MidのC#実装 (csharp)#af9a11fd98ca
public static class StringCompat
{
    /// <summary>VB.net の Mid 相当。1ベース起点、範囲外は空文字。</summary>
    public static string Mid(string s, int start, int length)
    {
        if (string.IsNullOrEmpty(s) || length <= 0) return string.Empty;
        // VB.net は 1 ベースなので 0 ベースに変換
        int startIndex = start - 1;
        if (startIndex < 0) startIndex = 0;
        if (startIndex >= s.Length) return string.Empty;
 
        int safeLen = Math.Min(length, s.Length - startIndex);
        return s.Substring(startIndex, safeLen);
    }
 
    /// <summary>VB.net の Mid(lengthなし)相当。指定位置から末尾まで。</summary>
    public static string Mid(string s, int start)
    {
        if (string.IsNullOrEmpty(s)) return string.Empty;
        int startIndex = start - 1;
        if (startIndex < 0) startIndex = 0;
        if (startIndex >= s.Length) return string.Empty;
        return s.Substring(startIndex);
    }
}
▸ この snippet は実行結果未収録
▸ 実行結果は未収録です
  • id: #af9a11fd98ca
  • lines: 25
  • extracted: 2026-06-10

Source収録記事

この snippet は記事の「最短対処:C#用のヘルパメソッド3点(コピペで動く) / ヘルパ2: MidのC#実装」セクションに登場する。コードの前後の文脈・ハマりどころの解説は記事本文で。

同じ記事から

6
C#
// NGパターン:直訳
string r = s.Substring(s.Length - 3);                // "cde" だが s が短いと例外
string r2 = "ab".Substring("ab".Length - 5);         // ArgumentOutOfRangeException
string r3 = ((string)null).Substring(((string)null).Length - 3); // NRE
未収録

Rightの仕様差

#3b80a0da3253
C#
public static class StringCompat
{
    /// <summary>VB.net の Right 相当。null・長さオーバーフロー・負値を吸収。</summary>
    public static string Right(string s, int length)
未収録

ヘルパ1: RightのC#実装

#d3eb9db0ae6a
C#
string r1 = StringCompat.Right("abcde", 3);    // "cde"
string r2 = StringCompat.Right("ab", 5);       // "ab"
string r3 = StringCompat.Right(null, 3);       // ""
未収録

ヘルパ1: RightのC#実装

#45fda6516d55
C#
public static class StringCompat
{
    /// <summary>VB.net の Left 相当。null・長さオーバーフロー・負値を吸収。</summary>
    public static string Left(string s, int length)
未収録

ヘルパ3: LeftのC#実装

#33c0d3d82b20
C#
public static string RightByGrapheme(string s, int length)
{
    if (string.IsNullOrEmpty(s) || length <= 0) return string.Empty;
    var si = new System.Globalization.StringInfo(s);
未収録

全角文字・Surrogate Pairで末尾が壊れる

#f3681c003f30
C#
// バイト単位で取りたい場合(SJIS で固定長レコードを切る等)
byte[] bytes = System.Text.Encoding.GetEncoding("Shift_JIS").GetBytes(s);
byte[] slice = new byte[len];
Array.Copy(bytes, start, slice, 0, len);
未収録

文字数vsバイト数の混乱

#3a5a69353075
図鑑トップ