Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variable assignment within method parameter

Tags:

c#

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?)

like image 762
dav_i Avatar asked Sep 24 '13 10:09

dav_i


People also ask

Can you assign a variable to a method in Java?

Java 8 has introduced the idea of a Functional Interface, which allows you to essentially assign methods to variables. It includes a number of commonly-used interfaces as well. Common examples: Consumer<T> - a method that takes in T and returns void.

What does variable assignment mean?

Variable Assignment To "assign" a variable means to symbolically associate a specific piece of information with a name. Any operations that are applied to this "name" (or variable) must hold true for any possible values.

Can we assign a value to parameter?

Assigning a value to a parameter can be done in the following ways: From the command line using the -define along with the appropriate parameter and value. A separate -define option is required for each parameter you want to run. See Integrator from the Command Line.

How do you assign a value to a parameter in Python?

The assignment operator, denoted by the “=” symbol, is the operator that is used to assign values to variables in Python. The line x=1 takes the known value, 1, and assigns that value to the variable with name “x”. After executing this line, this number will be stored into this variable.


2 Answers

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.

like image 78
David Arno Avatar answered Oct 12 '22 22:10

David Arno


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.

like image 43
Frederik Gheysels Avatar answered Oct 13 '22 00:10

Frederik Gheysels