out (C#-Referenz)

Sie können das Schlüsselwort out in zwei Kontexten verwenden:

Das Schlüsselwort out ist besonders hilfreich, wenn eine Methode mehrere Werte zurückgeben muss, da mehrere out-Parameter verwendet werden können, z. B.:

    public void Main()
    {
        double radiusValue = 3.92781;
        //Calculate the circumference and area of a circle, returning the results to Main().
        CalculateCircumferenceAndArea(radiusValue, out double circumferenceResult, out areaResult);
        System.Console.WriteLine($"Circumference of a circle with a radius of {radiusValue} is {circumferenceResult}.");
        System.Console.WriteLine($"Are of a circle with a radius of {radiusValue} is {areaResult}.");
        Console.ReadLine();
    }

    //The calculation worker method.
    public static void CalculateCircumferenceAndArea(double radius, out double circumference, out double area)
    {
        circumference = 2 * Math.PI * radius;
        area = Math.PI * (radius * radius);
    }

Die folgenden Einschränkungen gelten für das Schlüsselwort out:

  • out-Parameter sind in asynchronen Methoden nicht zulässig.
  • out-Parameter sind in Iteratormethoden nicht zulässig.
  • Eigenschaften können nicht als out-Parameter übergeben werden.