dav_i
dav_i

Reputation: 28097

Variable assignment within method parameter

I've just found out (by discovering a bug) that you can do this:

string s = "3";
int i;
int.TryParse(s = "hello", out i); //returns false

Is there a legitimate use of using the returned value of an assignment?

(Obviously i++ is, but is this the same?)

Upvotes: 8

Views: 3300

Answers (5)

David Arno
David Arno

Reputation: 43254

Generally I'd avoid using the return value of an assignment as it can all too easily lead to had to spot bugs. However, there is one excellent use for the feature as hopefully illustrated below, lazy initialization:

class SomeClass
{
    private string _value;

    public string Value { get { return _value ?? (_value = "hello"); } }
}

As of C# 6, this can be expressed using the => notation:

class SomeClass
{
    private string _value;

    public string Value => _value ?? (_value = "hello");
}

By using the ?? notation and the return value from the assignment, terse, yet readable, syntax can be used to only initialize the field and return it via a property when that property is called. In the above example, this isn't so useful, but within eg facades that need to be unit tested, only initializing those parts under test can greatly simplify the code.

Upvotes: 7

Frederik Gheysels
Frederik Gheysels

Reputation: 56934

This is legitimate.

s = "hello", is an expression which is evaluated / executed first, and the int.TryParse expression is executed after that.

Therefore, int.TryParse will use the content of 's' which is at that time "hello" and it's returning false.

Upvotes: 5

Soner Gönül
Soner Gönül

Reputation: 98740

Is there a legitimate use of using the returned value of an assignment?

Yes.

From = Operator (C# Reference)

The assignment operator (=) stores the value of its right-hand operand in the storage location, property, or indexer denoted by its left-hand operand and returns the value as its result.

That means = doesn't do assignment only, also it returns the value as an expression. Inside a method, your s reference now points to "hello" string not "3" anymore..

So,

int.TryParse(s = "hello", out i); 

is evaluated like;

int.TryParse("hello", out i); 

which since "hello" is not a valid integer, it returns false.

Upvotes: 3

Paul Ruane
Paul Ruane

Reputation: 38580

You are basically asking:

Is it useful that assignment to a variable can be used as a value?

One place where it is useful is for daisy-chaining variable assignments:

string a, b, c;
a = b = c = "hello";

Which is clearer when parenthesized:

string a, b, c;
a = (b = (c = "hello"));

If c = "hello" did not have the value hello, then the above would not be possible. It has limited use elsewhere but has no real downside.

Upvotes: 1

heijp06
heijp06

Reputation: 11788

An assignment is an expression just like any other. This is valid syntax.

For the same reason this is valid:

int i;
int j;
int k;

i = j = k = 42;

Upvotes: 4

Related Questions