YAKOVM
YAKOVM

Reputation: 10153

out arguments with not declared variable

I have a method

TrySplitStringTwoParts(string data, string separator, out string prefix, out string suffix)

it is called in the following way:

string data = "x.y", r1,r2;
TrySplitStringTwoParts(data, ".", out r1, out r2)

I am not interested to use r1 ,i.e. it is never used besides this call. Can I cange the way I call to the TrySplitStringTwoParts(data, ".", out r1, out r2) in order not to declare r1

Upvotes: 0

Views: 407

Answers (2)

Selman Genç
Selman Genç

Reputation: 101681

You can't do that for now. But that is one of the features that will be added in C# 6.See the roslyn Language feature implementation status page

-----------------------------------------------------------------
| Feature                 | Example                      | C#   |            
-----------------------------------------------------------------
| Declaration expressions | int.TryParse(s, out var x);  | Done |
-----------------------------------------------------------------

So then you will be able to do this:

TrySplitStringTwoParts(data, ".", out string r1, out string r2)

Ofcourse this will only move the declaration to another place,not declaring the variable is not possible.If you have a ref/out parameter then you have to declare and provide an argument.If you don't want this argument then maybe you should consider changing your method signature or use method overloading.

Upvotes: 4

Thorsten Dittmar
Thorsten Dittmar

Reputation: 56697

No, you can not. ref and out arguments must be passed in the call regardless of whether you actually use the variable later on or not.

Upvotes: 0

Related Questions