What is the boolean result of assign null to a variable - c#

I almost sure those two codes are equivalent, but not sure why.
First is the how I usually do it, i think the safe and more readable way.
string userLine = Console.ReadLine();
while (userLine != null) {
// do things with userLine
userLine = Console.ReadLine();
}
Second one works but not sure why. Because Im comparing an assigment to null.
string userLine;
while ((userLine = Console.ReadLine()) != null) {
// do things with userLine
}

I believe you are thinking that the assignment operation doesn't return any value or returns a Boolean value. That is not correct.
See: = Operator
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.
So your statement
while ((userLine = Console.ReadLine()) != null) {
is getting the value from Console.ReadLine assigning the result to userLine and returning the same value, which is compared with null.

The reason behind it works well is because, parenthesis () have highest operator precedence. Once assignment is done, compile will compare the the value of that variable to the null.
Having assignment in parenthesis chains your assignment. And that is the reason, it works.
Not only on Assignment, it works with return values too.
return (value = Console.ReadLine());
But yes, the first one is more readable approach.

The second code works because != operator has left associativity.
So that first
(userLine = Console.ReadLine())
execute, after that comparison happen.
And you are right the first approach is more readable.
If you want to get more information about associativity please refer https://msdn.microsoft.com/en-us/library/2bxt6kc4.aspx

In most likely scenario it is a function call and on return of the function the return value is stored either in done data GPR(general purpose register) or at top of stack. So, the next statement will just use that location and compare against null. Now you see fit generated code it doesn't make any difference... If you want to be sure, generate the assembly file during compilation and check for yourself. All compilers provide option to keep generated files...

Related

Does the ?? operator guarantee only to run the left-hand argument once?

For example, given this code:
int? ReallyComplexFunction()
{
return 2; // Imagine this did something that took a while
}
void Something()
{
int i = ReallyCleverFunction() ?? 42;
}
... is it guaranteed that the function will only be called once? In my test it's only called once, but I can't see any documentation stating I can rely on that always being the case.
Edit
I can guess how it is implemented, but c'mon: we're developers. We shouldn't be muddling through on guesses and assumptions. For example, will all future implementations be the same? Will another platform's implementation of the language be the same? That depends on the specifications of the language and what guarantees it offers. For example, a future or different platform implementation (not a good one, but it's possible) may do this in the ?? implementation:
return ReallyComplexFunction() == null ? 42 : ReallyComplexFunction();
That, would call the ReallyComplexFunction twice if it didn't return null. (although this looks a ridiculous implementation, if you replace the function with a nullable variable it looks quite reasonable: return a == null ? 42 : a)
As stated above, I know in my test it's only called once, but my question is does the C# Specification guarantee/specify that the left-hand side will only be called once? If so, where? I can't see any such mention in the C# Language Specification for ?? operator (where I originally looked for the answer to my query).
The ?? operator will evaluate the left side once, and the right side zero or once, depending on the result of the left side.
Your code
int i = ReallyCleverFunction() ?? 42;
Is equivalent to (and this is actually very close to what the compiler actually generates):
int? temp = ReallyCleverFunction();
int i = temp.HasValue ? temp.Value : 42;
Or more simply:
int i = ReallyCleverFunction().GetValueOrDefault(42);
Either way you look at it, ReallyCleverFunction is only called once.
The ?? operator has nothing to do with the left hand. The left hand is run first and then the ?? operator evaluates its response.
In your code, ReallyCleverFunction will only run once.
It will be only called once. If the value of ReallyCleverFunction is null, the value 42 is used, otherwise the returned value of ReallyCleverFunction is used.
It will evaluate the function, then evaluate the left value (which is the result of the function) of the ?? operator. There is no reason it would call the function twice.
It is called once and following the documentation I believe this should be sufficient to assume it is only called once:
It returns the left-hand operand if the operand is not null; otherwise
it returns the right operand.
?? operator
It will only be run once because the ?? operator is just a shortcut.
Your line
int i = ReallyCleverFunction() ?? 42;
is the same as
int? temp = ReallyCleverFunction();
int i;
if (temp != null)
{
i = temp.Value;
} else {
i = 42;
}
The compiler does the hard work.
Firstly, the answer is yes it does guarantee it will only evaluate it once, by inference in section 7.13 of the official C# language specification.
Section 7.13 always treats a as an object, therefore it must only take the return of a function and use that in the processing. It says the following about the ?? operator (emphasis added):
• If b is a dynamic expression, the result type is dynamic. At run-time, a is first evaluated. If a is not null, a is converted to dynamic, and this becomes the result. Otherwise, b is evaluated, and this becomes the result.
• Otherwise, if A exists and is a nullable type and an implicit conversion exists from b to A0, the result type is A0. At run-time, a is first evaluated. If a is not null, a is unwrapped to type A0, and this becomes the result. Otherwise, b is evaluated and converted to type A0, and this becomes the result.
• Otherwise, if A exists and an implicit conversion exists from b to A, the result type is A. At run-time, a is first evaluated. If a is not null, a becomes the result. Otherwise, b is evaluated and converted to type A, and this becomes the result.
• Otherwise, if b has a type B and an implicit conversion exists from a to B, the result type is B. At run-time, a is first evaluated. If a is not null, a is unwrapped to type A0 (if A exists and is nullable) and converted to type B, and this becomes the result. Otherwise, b is evaluated and becomes the result.
As a side-note the link given at the end of the question is not the C# language specification despite it's first ranking in a Google Search for the "C# language specification".

C#: Order of execution of operands in an IF statement

I came across some statements while surfing the .net source:
If( null != name)
If( false == check())
what is the difference between (name != null) and (Check() == false) statements from the above statements?
Can any one get me clear of this? Please.
I'm sure this is a duplicate, but I can't find it right now.
Code with the constant first is usually written by developers with an (old) background in C, where you might write this:
if (NULL == x)
instead of this:
if (x == NULL)
just in case you made a typo like this:
if (x = NULL) // Valid, but doesn't do what you want.
In most cases in C#, you don't need to do this - because the condition in an if statement has to be convertible to bool.
It would make a difference when you're comparing to a Boolean constant:
if ((Check() = false) // Eek!
... which is one reason to just write:
if (!Check())
Basically, putting the variable first is generally more readable - and in C# the reason for putting the constant first is almost never applicable anyway. (Modern C and C++ compilers will usually give you a warning anyway, so it's no longer a great idea in those languages either, as far as I'm aware...)
In terms of the order of evaluation, there is a theoretical difference in that the left-hand operand will be evaluated before the right-hand operand... but as the constants null and false don't have any side-effects, there's no real difference.
I think this style comes with C/C++ background, where the operator = which can also be used inside if statement, which could be used for comparison as well as assignment.
The statement
if( null != name) is same as if(name != null), so as the other statement
To safeguard from mistakenly assigning the value to the left hand side, this style of check is used in C/C++,
Take a look Coding Horror Yoda Conditions
Using if(constant == variable) instead of if(variable == constant),
like if(4 == foo). Because it's like saying "if blue is the sky" or
"if tall is the man".
The odd reversal looks like it was written by a C/C++ programmer... basically, in C/C++, if you accidentally type:
if(name = null)
instead of
if(name == null)
then that compiles and changes the value to null when invoked. A C/C++ habit to avoid this mistake is to use a constant such as null / false always on the left. This is because you can't reassign a constant, so it generates a compiler error if you use = instead of ==. In C# it (if(a = null)) doesn't usually compile, so that is not a concern.
There is no difference re the position here - both sides are evaluated. Idiomatic C# for this would be simply:
if(name != null) ...
if(!check()) ...

Is it a good practice not to use returned value of a method?

Here's my method:
public static bool ValidateAddressCount(ref long o_addressCount)
{
// o_addressCount is modified here
//return true or false
}
I've reached some case when i don't care what the method returns, i just need the o_adressCount
Is it a good practice to use this method in the following way:
long addressCount = 0;
ValidateAddressCount(ref addressCount); //without assigning the returned value to any variable
//use address count
Also, can anyone explain why this works in .net?
Thank you
Its upto the developer. No hard rules in it.
Like in bool int.TryParse(string s, out int a){}
When we pass a value to be converted into int value it returns a bool value and uses the out variable to send converted value.
Sometimes we need to check whether it has been converted or not. That's where we use return value.
string str = "1";
int a = 0;
if(int.TryParse(str, out a))
MessageBox.Show("Converted");
else
MessageBox.Show("Not Converted");
Tryparse can be used simply as
bool b = int.TryParse(str, out a);
Let's say bool value returned is of no use to me. Then why waste memory by creating a variable(b), assigning it a value and not using it. So i will write it as
int.TryParse(str, out a);
Why it works is easy:
long addressCount = 0;
ValidateAddressCount(ref addressCount);
is of the same form as
long addressCount = 0;
true;
Any <expression> ; is a valid statement.
There is a valid question here though:
Why is there no warning for this syntax which is quite likely a mistake?
Because in general it is not a good practice to ignore a return value.
This works because you declared a method with return-value, which means that you may want care about that return-value, but it's not mandatory option.
Use ref/out when calling method want the changes of called method in passed parameter.
Otherwise, it's not a good choice to use ref/out.
You should use dynamic object/tuple if want to return more than one value from called method.
You do not have to use the result of the method, you can just call it for its side effect. However, it's usually a good idea to avoid using ref, if you can. In your case, you can just return long?.
No you dont need to assign the return value.. but in my opinion, method as validateSomething(object) should have a return value if the object is valid or not and it shoud be important to check for the return value.
If the method does something with the object, it shouldnt be called just validateSomething(object), but validateAndChangeSomething(object)... now it is confusing what it is doing and what is the primary output of the validation: the return value or the modified object..
Whilst what you have written works, I don't think it's particularly obvious what your method is doing.
Things have moved on a bit since I first started coding but I believe that nowdays it good practice to make your code readable to humans first and then comment the hell out of it if you really have to do something unexpected.
With that in mind, I'd tweak your code to provide a property to obtain the count and modify the method so that you wouldn't need a parameter.
I know this doesn't answer the "use a method and ignore the return type" part of your question but I think that's subjective on what your are doing at the time.

?? Operator with 2 strings?

In this .NET code:
return Redirect("~/Home" ?? "JaneDoe");
If I'm reading the docs right, the "??" operator appears to operate similarly to IsNull in SQL:
IsNull("~/Home", "JaneDoe")
"~Home" and "JaneDoe" are simply strings, right? There's no condition in the return Redirect code where "JaneDoe" will be what's passed into "Redirect", is there? I'm not sure what to make of this snippet, I can only presume it's a placeholder for something to come later.
This code is from a .NET-MVC project in development, part of a .cs file that is a LoginController.
Yes, this is just bad code. That will always be equivalent to
return Redirect("~/Home");
I'm slightly surprised the compiler isn't smart enough to give a warning about it, to be honest. It would be nice if it could tell that a constant non-null expression was being used on the LHS of the null-coalescing operator.
The ?? operator is called the null-coalescing operator and is used to define a default value for a nullable value types as well as reference types. It returns the left-hand operand if it is not null; otherwise it returns the right operand.
In your case, it will never return JaneDoe
Yes, you're reading it correctly. That will always return "~/Home", presumably it was planned to change it to a variable at some point.
This would always use the "~/Home" string. The null-coalescing operator (??) selects the left side if it is non-null, or the right side if it is null.
Correct, the expression will never return "JaneDoe".

What is the difference in string.Equals("string") and "String".Equals(string)?

Is there any difference in following two lines of code that compares the string values.
string str = "abc";
if(str.Equals("abc"))
and
if("abc".Equals(str))
in the first line I am calling the equals method on string variable to compare it with string literal. The second line is vice versa. Is it just the difference of coding style or there is a difference in the way these two statements are processed by the compiler.
The only difference is that, in the first case, when you do:
str.Equals("abc")
If str is null, you'll get an exception at runtime. By doing:
"abc".Equals(str)
If str is null, you'll get false.
The difference is that in the second example, you will never get a NullReferenceException because a literal can't be null.
To add to the other answers: the static string.Equals("abc", str) method always avoids triggering a null reference exception, regardless of which order you pass the two strings.
As mmyers said, you the second example will not throw a NullReferenceException and while allowing the program to "appear" to run error free, may lead to unintended results.
Yes, the way the compiler processed the statements is different. The function equals for String in most languages follows the same guidlines. Here is a semicode:
override def Equals(that:String):Boolean //Should override Object.Equals
if(that==null) return false
for i from 0 to this.length
if(!this(i).Equals(that(i))) return false
return true
Normally, the method will fisrt check that that IS a String, and that this and that have the same length.
You can see, as others pointed out, that if that is null the method returns false. On the other hand, the method is part of of String so it cannot be called on null. That is why in your exampleif str is null you will get a NullReferenceException.
That being said, if you know both variables are non-null Strings of the same length, both statements will evaluate to the same in the same time.

Categories

Resources