C#のStringとstring、Int32とint 違いは・・・ない!

C#

先頭が大文字のStringと小文字のstring
いろいろなサンプルソースを眺めていると、文字列型としてStringを使っている人とstringを使う人がいる事に気付きます。C#は大文字と小文字を区別して扱うはずなのになにが違うのでしょう?


違いはありません。”全く同じもの”です。



先頭が大文字のString

先頭が大文字の String は正確には System.String です。
ソース内で単に String と書かれている場合はきっと using System; が宣言されているはずです。

System.String を詳しく見ていくと以下のようなクラスとして定義されている事が分かります。

namespace System
{
    public sealed class String : IComparable, ICloneable, IConvertible, IComparable<String>, IEnumerable<char>, IEnumerable, IEquatable<String>
    {
        public static readonly String Empty;
 
        public String(char[] value);
        public String(sbyte* value);
        public String(char* value);
        public String(char c, int count);
        public String(char[] value, int startIndex, int length);
        public String(sbyte* value, int startIndex, int length);
        public String(char* value, int startIndex, int length);
        public String(sbyte* value, int startIndex, int length, Encoding enc);
        
        public char this[int index] { get; }
        
        public int Length { get; }
 
      :
      :
     以下省略


先頭が小文字のstring

先頭が小文字の string 予約語(キーワード)として予め定義されている識別子です。
Visual Studio などを使っている場合、stringと書くと色が変わりますよね。

このstringキーワードは「System.String のエイリアス(別名)」なのです。
コンパイルすれば String も string も全く同じものになります。


他にもあるエイリアス

stringと同様にエイリアスをキーワードに定義しているものがいくつかあります。
  • bool    は System.Boolean と同じものです。
  • sbyte   は System.SByte   と同じものです。
  • byte    は System.Byte    と同じものです。
  • short   は System.Int16   と同じものです。
  • ushort  は System.UInt16  と同じものです。
  • int     は System.Int32   と同じものです。
  • uint    は System.UInt32  と同じものです。
  • long    は System.Int64   と同じものです。
  • ulong   は System.UInt64  と同じものです。
  • char    は System.Char    と同じものです。
  • float   は System.Single  と同じものです。
  • double  は System.Double  と同じものです。
  • decimal は System.Decimal と同じものです。
  • object  は System.Object  と同じものです。

基本のデータ型などを便利に書けるようキーワードに定義してくれているのですね。



コメント