この記事は機械翻訳されています。英語版の記事を表示するには、[英語] のチェック ボックスをオンにしてください。また、テキストにマウス ポインターを合わせると、ポップアップ ウィンドウに英語のテキストを表示することもできます。
翻訳
英語

ArgumentOutOfRangeException クラス

 

公開日: 2016年10月

引数の値が、呼び出されたメソッドで定義されている許容範囲外である場合にスローされる例外。

名前空間:   System
アセンブリ:  mscorlib (mscorlib.dll 内)

System.Object
  System.Exception
    System.SystemException
      System.ArgumentException
        System.ArgumentOutOfRangeException

[SerializableAttribute]
[ComVisibleAttribute(true)]
public class ArgumentOutOfRangeException : ArgumentException, 
	ISerializable

名前説明
System_CAPS_pubmethodArgumentOutOfRangeException()

ArgumentOutOfRangeException クラスの新しいインスタンスを初期化します。

System_CAPS_protmethodArgumentOutOfRangeException(SerializationInfo, StreamingContext)

シリアル化したデータを使用して、ArgumentOutOfRangeException クラスの新しいインスタンスを初期化します。

System_CAPS_pubmethodArgumentOutOfRangeException(String)

新しいインスタンスを初期化、ArgumentOutOfRangeExceptionこの例外の原因となるパラメーターの名前を持つクラス。

System_CAPS_pubmethodArgumentOutOfRangeException(String, Exception)

新しいインスタンスを初期化、ArgumentOutOfRangeException指定したエラー メッセージ、およびこの例外の原因となった例外を持つクラス。

System_CAPS_pubmethodArgumentOutOfRangeException(String, Object, String)

新しいインスタンスを初期化、ArgumentOutOfRangeExceptionパラメーターと共にクラスの名前、引数、および指定したエラー メッセージの値。

System_CAPS_pubmethodArgumentOutOfRangeException(String, String)

新しいインスタンスを初期化、ArgumentOutOfRangeExceptionこの例外と指定したエラー メッセージを原因となったパラメーターの名前を持つクラス。

名前説明
System_CAPS_pubpropertyActualValue

この例外を引き起こした引数の値を取得します。

System_CAPS_pubpropertyData

例外に関する追加のユーザー定義情報を提供する、キー/値ペアのコレクションを取得します。(Exception から継承されます。)

System_CAPS_pubpropertyHelpLink

この例外に関連付けられているヘルプ ファイルへのリンクを取得または設定します。(Exception から継承されます。)

System_CAPS_pubpropertyHResult

特定の例外に割り当てられているコード化数値である HRESULT を取得または設定します。(Exception から継承されます。)

System_CAPS_pubpropertyInnerException

現在の例外の原因となる Exception インスタンスを取得します。(Exception から継承されます。)

System_CAPS_pubpropertyMessage

引数の値が null の場合は、エラー メッセージと、無効な引数の値またはエラー メッセージのみの文字列形式を取得します。(ArgumentException.Message をオーバーライドします。)

System_CAPS_pubpropertyParamName

この例外の原因である引数の名前を取得します。(ArgumentException から継承されます。)

System_CAPS_pubpropertySource

エラーの原因となるアプリケーションまたはオブジェクトの名前を取得または設定します。(Exception から継承されます。)

System_CAPS_pubpropertyStackTrace

呼び出し履歴で直前のフレームの文字列形式を取得します。(Exception から継承されます。)

System_CAPS_pubpropertyTargetSite

現在の例外がスローされたメソッドを取得します。(Exception から継承されます。)

名前説明
System_CAPS_pubmethodEquals(Object)

指定したオブジェクトが、現在のオブジェクトと等しいかどうかを判断します。(Object から継承されます。)

System_CAPS_protmethodFinalize()

オブジェクトがガベージ コレクションにより収集される前に、そのオブジェクトがリソースを解放し、その他のクリーンアップ操作を実行できるようにします。 (Object から継承されます。)

System_CAPS_pubmethodGetBaseException()

派生クラスでオーバーライドされた場合、それ以後に発生する 1 つ以上の例外の主要な原因である Exception を返します。(Exception から継承されます。)

System_CAPS_pubmethodGetHashCode()

既定のハッシュ関数として機能します。(Object から継承されます。)

System_CAPS_pubmethodGetObjectData(SerializationInfo, StreamingContext)

セット、 SerializationInfo 無効な引数の値と追加の例外情報を持つオブジェクト。(ArgumentException.GetObjectData(SerializationInfo, StreamingContext) をオーバーライドします。)

System_CAPS_pubmethodGetType()

現在のインスタンスのランタイム型を取得します。(Exception から継承されます。)

System_CAPS_protmethodMemberwiseClone()

現在の Object の簡易コピーを作成します。(Object から継承されます。)

System_CAPS_pubmethodToString()

現在の例外の文字列形式を作成して返します。(Exception から継承されます。)

名前説明
System_CAPS_proteventSerializeObjectState

例外がシリアル化され、例外に関するシリアル化されたデータを含む例外状態オブジェクトが作成されたときに発生します。(Exception から継承されます。)

An T:System.ArgumentOutOfRangeException exception is thrown when a method is invoked and at least one of the arguments passed to the method is not null and contains an invalid value that is not a member of the set of values expected for the argument. The P:System.ArgumentException.ParamName property identifies the invalid argument, and the P:System.ArgumentOutOfRangeException.ActualValue property, if a value is present, identifies the invalid value.

Typically, an T:System.ArgumentOutOfRangeException results from developer error. Instead of handling the exception in a try/catch block, you should eliminate the cause of the exception or, if the argument is returned by a method call or input by the user before being passed to the method that throws the exception, you should validate arguments before passing them to the method.

ArgumentOutOfRangeException is used extensively by:

  • Classes in the N:System.Collections and N:System.IO namespaces.

  • The T:System.Array class.

  • String manipulation methods in the T:System.String class.

The conditions in which an T:System.ArgumentOutOfRangeException exception is thrown include the following:

You are retrieving the member of a collection by its index number, and the index number is invalid.

This is the most common cause of an T:System.ArgumentOutOfRangeException exception. Typically, the index number is invalid for one of three reasons:

  • The collection has no members, and your code assumes that it does. The following example attempts to retrieve the first element of a collection that has no elements:

    using System;
    using System.Collections.Generic;
    
    public class Example
    {
       public static void Main()
       {
          var list = new List<String>();
          Console.WriteLine("Number of items: {0}", list.Count);
          try {
             Console.WriteLine("The first item: '{0}'", list[0]);
          }
          catch (ArgumentOutOfRangeException e) {
             Console.WriteLine(e.Message);
          }
       }
    }
    // The example displays the following output:
    //   Number of items: 0
    //   Index was out of range. Must be non-negative and less than the size of the collection.
    //   Parameter name: index
    

    To prevent the exception, check whether the collection's Count property is greater than zero before attempting to retrieve any members, as the following code fragment does.

    if (list.Count > 0)
       Console.WriteLine("The first item: '{0}'", list[0]);
    

    In some cases, this may occur because you are attempting to add a member to a collection by using an index that does not exist, rather than by calling the method, such as Add, that exists for this purpose. The following example attempts to add an element to a collection by using a non-existent index rather than calling the M:System.Collections.Generic.List`1.Add(`0) method.

    using System;
    using System.Collections.Generic;
    
    public class Example
    {
       public static void Main()
       {
          var numbers = new List<int>();
          numbers.AddRange( new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 20 } );
    
          var squares = new List<int>();
          for (int ctr = 0; ctr < numbers.Count; ctr++)
             squares[ctr] = (int) Math.Pow(numbers[ctr], 2); 
       }
    }
    // The example displays the following output:
    //    Unhandled Exception: System.ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.
    //    Parameter name: index
    //       at System.ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument argument, ExceptionResource resource)
    //       at Example.Main()
    

    The following code fragment corrects this error:

    var squares = new List<int>();
    for (int ctr = 0; ctr < numbers.Count; ctr++)
       squares.Add((int) Math.Pow(numbers[ctr], 2)); 
    
  • You're attempting to retrieve an item whose index is negative. This usually occurs because you've searched a collection for the index of a particular element and have erroneously assumed that the search is successful. In the following example, the call to the M:System.Collections.Generic.List`1.FindIndex(System.Predicate{`0}) method fails to find a string equal to "Z" and so returns -1. However, this is an invalid index value.

    using System;
    using System.Collections.Generic;
    
    public class Example
    {
       public static void Main()
       {
          var list = new List<String>(); 
          list.AddRange( new String[] { "A", "B", "C" } );
          // Get the index of the element whose value is "Z".
          int index = list.FindIndex((new StringSearcher("Z")).FindEquals);
          try {
             Console.WriteLine("Index {0} contains '{1}'", index, list[index]); 
          }
          catch (ArgumentOutOfRangeException e) {
             Console.WriteLine(e.Message);
          }
       }
    }
    
    internal class StringSearcher
    {
       String value;
    
       public StringSearcher(String value)
       {
          this.value = value;
       }
    
       public bool FindEquals(String s) 
       {
          return s.Equals(value, StringComparison.InvariantCulture); 
       }
    }
    // The example displays the following output:
    //   Index was out of range. Must be non-negative and less than the size of the collection.
    //   Parameter name: index
    

    To prevent the exception, check that the search is successful by making sure that the returned index is greater than or equal to zero before attempting to retrieve the item from the collection, as the following code fragment does.

    // Get the index of the element whose value is "Z".
    int index = list.FindIndex((new StringSearcher("Z")).FindEquals);
    if (index >= 0)
       Console.WriteLine("'Z' is found at index {0}", list[index]); 
    
  • You're attempting to retrieve an element whose index is equal to the value of the collection's Count property, as the following example illustrates.

    using System;
    using System.Collections.Generic;
    
    public class Example
    {
       public static void Main()
       {
          var list = new List<String>(); 
          list.AddRange( new String[] { "A", "B", "C" } );
          try {
             // Display the elements in the list by index.
             for (int ctr = 0; ctr <= list.Count; ctr++) 
                Console.WriteLine("Index {0}: {1}", ctr, list[ctr]);
          } 
          catch (ArgumentOutOfRangeException e) {
             Console.WriteLine(e.Message);
          }
       }
    }
    // The example displays the following output:
    //   Index 0: A
    //   Index 1: B
    //   Index 2: C
    //   Index was out of range. Must be non-negative and less than the size of the collection.
    //   Parameter name: index
    

    Because collections in the .NET Framework use zero-based indexing, the first element of the collection is at index 0, and the last element is at index Count - 1. You can eliminate the error by ensuring that you access the last element at index Count - 1, as the following code does.

    // Display the elements in the list by index.
    for (int ctr = 0; ctr < list.Count; ctr++) 
       Console.WriteLine("Index {0}: {1}", ctr, list[ctr]);
    
You are attempting to perform a string operation by calling a string manipulation method, and the starting index does not exist in the string.

Overloads of methods such as such as M:System.String.Compare(System.String,System.String), M:System.String.CompareOrdinal(System.String,System.Int32,System.String,System.Int32,System.Int32), M:System.String.IndexOf(System.String), M:System.String.IndexOfAny(System.Char[]), M:System.String.Insert(System.Int32,System.String), M:System.String.LastIndexOf(System.String), M:System.String.LastIndexOfAny(System.Char[]), M:System.String.Remove(System.Int32), or M:System.String.Substring(System.Int32) that allow you to specify the starting index of the operation require that the index be a valid position within the string. Valid indexes range from 0 to P:System.String.Length - 1.

There are four common causes of this T:System.ArgumentOutOfRangeException exception:

  • You are working with an empty string., or F:System.String.Empty. Because its P:System.String.Length property returns 0, any attempt to manipulate it by index throws an T:System.ArgumentOutOfRangeException exception. The following example, defines a GetFirstCharacter method that returns the first character of a string. If the string is empty, as the final string passed to the method is, the method throws an T:System.ArgumentOutOfRangeException exception.

    using System;
    
    public class Example
    {
       public static void Main()
       {
           String[] words = { "the", "today", "tomorrow", " ", "" };
           foreach (var word in words)
              Console.WriteLine("First character of '{0}': '{1}'", 
                                word, GetFirstCharacter(word));
       }
    
       private static char GetFirstCharacter(String s)
       {
          return s[0];
       }
    }
    // The example displays the following output:
    //    First character of //the//: //t//
    //    First character of //today//: //t//
    //    First character of //tomorrow//: //t//
    //    First character of // //: // //
    //    
    //    Unhandled Exception: System.IndexOutOfRangeException: Index was outside the bounds of the array.
    //       at Example.Main()
    

    You can eliminate the exception by testing whether the string's P:System.String.Length is greater than zero or by calling the M:System.String.IsNullOrEmpty(System.String) method to ensure that the string is not null or empty. The following code fragment does the latter. In this case, if the string is null or empty, the GetFirstCharacter method returns U+0000.

    static char GetFirstCharacter(String s)
    {
       if (String.IsNullOrEmpty(s)) 
          return '\u0000';
       else   
          return s[0];
    }
    
  • You're manipulating a string based on the position of a substring within that string, and you've failed to determine whether the substring was actually found.

    The following example extracts the second word of a two-word phrase. It throws an T:System.ArgumentOutOfRangeException exception if the phrase consists of only one word, and therefore does not contain an embedded space character. This occurs because the call to the M:System.String.IndexOf(System.String) method returns -1 to indicate that the search failed, and this invalid value is then passed to the M:System.String.Substring(System.Int32) method.

    using System;
    
    public class Example
    {
       public static void Main()
       {
          String[] phrases = { "ocean blue", "concerned citizen", 
                               "runOnPhrase" };
          foreach (var phrase in phrases)
             Console.WriteLine("Second word is {0}", GetSecondWord(phrase));
       }
    
       static String GetSecondWord(String s)
       {
          int pos = s.IndexOf(" ");
          return s.Substring(pos).Trim();
       }
    }
    // The example displays the following output:
    //    Second word is blue
    //    Second word is citizen
    //    
    //    Unhandled Exception: System.ArgumentOutOfRangeException: StartIndex cannot be less than zero.
    //    Parameter name: startIndex
    //       at System.String.Substring(Int32 startIndex, Int32 length)
    //       at Example.GetSecondWord(String s)
    //       at Example.Main()
    

    To eliminate the exception, validate the value returned by the string search method before calling the string manipulation method.

    using System;
    
    public class Example
    {
       public static void Main()
       {
          String[] phrases = { "ocean blue", "concerned citizen", 
                               "runOnPhrase" };
          foreach (var phrase in phrases) {
             String word = GetSecondWord(phrase);
             if (! String.IsNullOrEmpty(word))
                Console.WriteLine("Second word is {0}", word);
          }   
       }
    
       static String GetSecondWord(String s)
       {
          int pos = s.IndexOf(" ");
          if (pos >= 0)
             return s.Substring(pos).Trim();
          else
             return String.Empty;   
       }
    }
    // The example displays the following output:
    //       Second word is blue
    //       Second word is citizen
    
You've attempted to extract a substring that is outside the range of the current string.

The methods that extract substrings all require that you specify the starting position of the substring and, for substrings that do not continue to the end of the string, the number of characters in the substring. Note that this is not the index of the last character in the substring.

An T:System.ArgumentOutOfRangeException exception is typically thrown in this case because you've incorrectly calculated the number of characters in the substring. If you are using a search method like M:System.String.IndexOf(System.Char) to identify the starting and ending positions of a substring:

  • If the character in the ending position returned by M:System.String.IndexOf(System.Char) is to be included in the substring, the ending position of the substring is given by the formula

    endIndex - startIndex + 1
    
  • If the character in the ending position returned by M:System.String.IndexOf(System.Char) is to be excluded from the substring, the ending position of the substring is given by the formula

    endIndex - startIndex 
    

The following example defines a FindWords method that uses the M:System.String.IndexOfAny(System.Char[],System.Int32) method to identify space characters and punctuation marks in a string and returns an array that contains the words found in the string.

using System;
using System.Collections.Generic;

public class Example
{
   public static void Main()
   {
      String sentence = "This is a simple, short sentence.";
      Console.WriteLine("Words in '{0}':", sentence);
      foreach (var word in FindWords(sentence))
         Console.WriteLine("   '{0}'", word);
   }

   static String[] FindWords(String s)
   {
      int start = 0, end = 0;
      Char[] delimiters = { ' ', '.', ',', ';', ':', '(', ')' };
      var words = new List<String>();

      while (end >= 0) {
         end = s.IndexOfAny(delimiters, start);
         if (end >= 0) {
            if (end - start > 0)
               words.Add(s.Substring(start, end - start)); 

            start = end++;
         }
         else {
            if (start < s.Length - 1)
               words.Add(s.Substring(start));
         }
      }    
      return words.ToArray();                         
   }
}
// The example displays the following output:
//       Words in 'This is a simple, short sentence.':
//          'This'
//          'is'
//          'a'
//          'simple'
//          'short'
//          'sentence'
You have passed a negative number to a method with an argument that requires only positive numbers and zero, or you have passed either a negative number or zero to a method with an argument that requires only positive numbers.

For example, the M:System.Array.CreateInstance(System.Type,System.Int32,System.Int32,System.Int32) method requires that you specify the number of elements in each dimension of a two-dimensional array; valid values for each dimension can range from 0 to F:System.Int32.MaxValue. But because the dimension argument in the following example has a negative value, the method throws an T:System.ArgumentOutOfRangeException exception.

using System;

public class Example
{
   public static void Main()
   {
      int dimension1 = 10;
      int dimension2 = -1;
      try {
         Array arr = Array.CreateInstance(typeof(String), 
                                          dimension1, dimension2);
      }
      catch (ArgumentOutOfRangeException e) {
         if (e.ActualValue != null)
            Console.WriteLine("{0} is an invalid value for {1}: ", e.ActualValue, e.ParamName);
         Console.WriteLine(e.Message);
      }
   }
}
// The example displays the following output:
//     Non-negative number required.
//     Parameter name: length2

To correct the error, ensure that the value of the invalid argument is non-negative. You can do this by providing a valid value, as the following code fragment does.

int dimension1 = 10;
int dimension2 = 10;
Array arr = Array.CreateInstance(typeof(String), 
                                 dimension1, dimension2);   

You can also validate the input and, if it is invalid, take some action. The following code fragment displays an error message instead of calling the method.

if (dimension1 < 0 || dimension2 < 0) {
   Console.WriteLine("Unable to create the array.");
   Console.WriteLine("Specify non-negative values for the two dimensions.");
}   
else {
   arr = Array.CreateInstance(typeof(String), 
                              dimension1, dimension2);   
}
A race condition exists in an app that is multithreaded or has tasks that execute asynchronously and that updates an array or collection.

The following example uses a T:System.Collections.Generic.List`1 object to populate a collection of Continent objects. It throws an T:System.ArgumentOutOfRangeException exception if the example attempts to display the seven items in the collection before the collection is fully populated.

using System;
using System.Collections.Generic;
using System.Threading;

public class Continent
{
   public String Name { get; set; }
   public int Population { get; set; }
   public Decimal Area { get; set; }   
}

public class Example
{
   static List<Continent> continents = new List<Continent>();
   static String msg; 

   public static void Main()
   {
      String[] names = { "Africa", "Antarctica", "Asia", 
                         "Australia", "Europe", "North America",
                         "South America" };
      // Populate the list.
      foreach (var name in names) {
         var th = new Thread(PopulateContinents);
         th.Start(name);
      }              
      Console.WriteLine(msg);
      Console.WriteLine();

      // Display the list.
      for (int ctr = 0; ctr < names.Length; ctr++) {
         var continent = continents[ctr];
         Console.WriteLine("{0}: Area: {1}, Population {2}", 
                           continent.Name, continent.Population,
                           continent.Area);
      }
   }

   private static void PopulateContinents(Object obj)
   {
      String name = obj.ToString();
      msg += String.Format("Adding '{0}' to the list.\n", name);
      var continent = new Continent();
      continent.Name = name;
      // Sleep to simulate retrieving remaining data.
      Thread.Sleep(50);
      continents.Add(continent);
   }
}
// The example displays output like the following:
//    Adding //Africa// to the list.
//    Adding //Antarctica// to the list.
//    Adding //Asia// to the list.
//    Adding //Australia// to the list.
//    Adding //Europe// to the list.
//    Adding //North America// to the list.
//    Adding //South America// to the list.
//    
//    
//    
//    Unhandled Exception: System.ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.
//    Parameter name: index
//       at System.ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument argument, ExceptionResource resource)
//       at Example.Main()

In this case, two resources are accessed from multiple threads:

  • The continents collection. Its M:System.Collections.Generic.List`1.Add(`0) method is called from multiple threads. In addition, the main or primary thread assumes the collection is fully populated with seven elements when it iterates its members.

  • The msg string, which is concatenated from multiple threads.

To correct the error, ensure that shared state is accessed in a thread-safe way, as follows.

  • if your app uses an array or collection object, consider using a thread-safe collection class, such as the types in the N:System.Collections.Concurrent namespace or the System.Collections.Immutable out-of-band release.

  • Ensure that shared state (that is, resources that can be accessed by multiple threads) is accessed in a thread-safe way, so that only one thread at a time has exclusive access to the resources. A large number of classes, such as T:System.Threading.CountdownEvent, T:System.Threading.Interlocked, T:System.Threading.Monitor, and T:System.Threading.Mutex, are available to synchronize access to resources. For more information, see Managed Threading. In addition, language support is available through the lock statement in C# and the SyncLock construct in Visual Basic.

The following example addresses the T:System.ArgumentOutOfRangeException exception and the other issues from the previous example. It replaces the T:System.Collections.Generic.List`1 object with a T:System.Collections.Concurrent.ConcurrentBag`1 object to ensure that access to the collection is thread-safe, uses a T:System.Threading.CountdownEvent object to ensure that the application thread continues only after other threads have executed, and uses a lock to ensure that only one thread can access the msg variable at a time.

using System;
using System.Collections.Concurrent;
using System.Threading;

public class Continent
{
   public String Name { get; set; }
   public int Population { get; set; }
   public Decimal Area { get; set; }   
}

public class Example
{
   static ConcurrentBag<Continent> continents = new ConcurrentBag<Continent>();
   static CountdownEvent gate;
   static String msg = String.Empty;

   public static void Main()
   {
      String[] names = { "Africa", "Antarctica", "Asia", 
                         "Australia", "Europe", "North America",
                         "South America" };
      gate = new CountdownEvent(names.Length);

      // Populate the list.
      foreach (var name in names) {
         var th = new Thread(PopulateContinents);
         th.Start(name);
      }              

      // Display the list.
      gate.Wait();
      Console.WriteLine(msg);
      Console.WriteLine();

      var arr = continents.ToArray();
      for (int ctr = 0; ctr < names.Length; ctr++) {
         var continent = arr[ctr];
         Console.WriteLine("{0}: Area: {1}, Population {2}", 
                           continent.Name, continent.Population,
                           continent.Area);
      }
   }

   private static void PopulateContinents(Object obj)
   {
      String name = obj.ToString();
      lock(msg) { 
         msg += String.Format("Adding '{0}' to the list.\n", name);
      }
      var continent = new Continent();
      continent.Name = name;
      // Sleep to simulate retrieving remaining data.
      Thread.Sleep(25);
      continents.Add(continent);
      gate.Signal();
   }
}
// The example displays output like the following:
//       Adding 'Africa' to the list.
//       Adding 'Antarctica' to the list.
//       Adding 'Asia' to the list.
//       Adding 'Australia' to the list.
//       Adding 'Europe' to the list.
//       Adding 'North America' to the list.
//       Adding 'South America' to the list.
//       
//       
//       Africa: Area: 0, Population 0
//       Antarctica: Area: 0, Population 0
//       Asia: Area: 0, Population 0
//       Australia: Area: 0, Population 0
//       Europe: Area: 0, Population 0
//       North America: Area: 0, Population 0
//       South America: Area: 0, Population 0

ArgumentOutOfRangeException uses the HRESULT COR_E_ARGUMENTOUTOFRANGE, which has the value 0x80131502.

For a list of initial property values for an instance of T:System.ArgumentOutOfRangeException, see the T:System.ArgumentOutOfRangeException constructors.

The following example defines a class to contain information about an invited guest. If the guest is younger than 21, an T:System.ArgumentOutOfRangeException exception is thrown.

using System;

class Program
{
    static void Main(string[] args)
    {
        try
        {
            Guest guest1 = new Guest("Ben", "Miller", 17);
            Console.WriteLine(guest1.GuestInfo());
        }
        catch (ArgumentOutOfRangeException outOfRange)
        {

            Console.WriteLine("Error: {0}", outOfRange.Message);
        }
    }
}

class Guest
{
    private string FirstName;
    private string LastName;
    private int Age;

    public Guest(string fName, string lName, int age)
    {
        FirstName = fName;
        LastName = lName;
        if (age < 21)
            throw new ArgumentOutOfRangeException("age","All guests must be 21-years-old or older.");
        else
            Age = age;
    }

    public string GuestInfo()
    {
        string gInfo = FirstName + " " + LastName + ", " + Age.ToString();
        return(gInfo);
    }
}

ユニバーサル Windows プラットフォーム
8 以降で使用可能
.NET Framework
1.1 以降で使用可能
ポータブル クラス ライブラリ
サポート対象: 移植可能 .NET プラットフォーム
Silverlight
2.0 以降で使用可能
Windows Phone Silverlight
7.0 以降で使用可能
Windows Phone
8.1 以降で使用可能

この型のパブリック static (Visual Basic では Shared ) メンバーはスレッド セーフです。インスタンス メンバーの場合は、スレッド セーフであるとは限りません。

トップに戻る
表示: