Mehmet Resul Akyuz
Mehmet Resul Akyuz

Reputation: 95

I want to use an out parameter with string variable

I want to use an out parameter with string variable.

For Example:

string Url = "https://learn.microsoft.com/tr-tr/dotnet/csharp/language-reference/keywords/out-parameter-modifier"

string BaseUrl = this.DecompositionUrl(out Url).BaseUrl;
string ServiceUrl = this.DecompositioUrl(out Url).ServiceUrl; 

I want to using a method like this.

 public static string DecompositionUrl(out string Urlr)
    {
        // enter here  :
        BaseUrl = Urlr.Substring(0,40);
        ServiceUrl = Urlr.Substring(40,Urlr.Length);
    }

When returned my DecompositionUrl I want to set BaseUrl and ServiceUrl

Upvotes: 0

Views: 176

Answers (2)

Hans Kilian
Hans Kilian

Reputation: 25189

C# 7 allows you to return a 'tuple' as the result of a method like this

   public static (string, string) DecompositionUrl(string url)
    {
        var baseUrl = ...;
        var serviceUrl = ...;
        return (baseUrl, serviceUrl);
    }

You can then use it like this

(string baseUrl, string serviceUrl) = DecompositionUrl("https://learn.microsoft.com/tr-tr/dotnet/csharp/language-reference/keywords/out-parameter-modifier");

I think that's better than using the out keyword since it's clearer what's input and what's output.

Upvotes: 3

Douglas
Douglas

Reputation: 54887

You need to declare out parameters for the two values that you intend to return from your method: baseUrl and serviceUrl. The source url needs to be passed in through an ordinary parameter (not out).

public static void DecompositionUrl(string url, out string baseUrl, out string serviceUrl)
{
    baseUrl = url.Substring(0, 40);
    serviceUrl = url.Substring(40);
}

You would then call your method like so:

string url = "https://learn.microsoft.com/tr-tr/dotnet/csharp/language-reference/keywords/out-parameter-modifier"
DecompositionUrl(url, out var baseUrl, our var serviceUrl);
Console.WriteLine($"Base URL is {baseUrl} and service URL is {serviceUrl}.");

Upvotes: 4

Related Questions