473,386 Members | 1,715 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,386 software developers and data experts.

Why does this code work?

Or seem to anyway.
=====
string abc;
if ((abc=getString()) != "")
{
MessageBox.Show(abc);
}

private string getString()
{
return "something";
}
=====
I get the MessageBox displayed. If I change != to == there's no MessageBox.

What is the != comparing, and how?
Nov 16 '05 #1
18 2230
"Daniel Billingsley" <dbillingsley@NO_durcon_SPAAMM.com> wrote in message news:uq*************@TK2MSFTNGP11.phx.gbl...
Or seem to anyway.
=====
string abc;
if ((abc=getString()) != "")
{
MessageBox.Show(abc);
}
As your parenthesis indicate, the first thing that happens is:
(abc=getString())
so, abc gets the value of "something"

Which is then tested to be != to "", which is true. "something" != "" so the messagebox shows. Why do you feel there it should be
otherwise?

--
Adam Clauss
ca*****@tamu.edu


private string getString()
{
return "something";
}
=====
I get the MessageBox displayed. If I change != to == there's no MessageBox.

What is the != comparing, and how?


Nov 16 '05 #2
Hi,

Since abc is assigned to the value returned by getString() and then that
value is compared to "" (condition validates to true), MessageBox is shown.
In case of ==, the condition validates to false and no messagebox.

"Daniel Billingsley" <dbillingsley@NO_durcon_SPAAMM.com> wrote in message
news:uq*************@TK2MSFTNGP11.phx.gbl...
Or seem to anyway.
=====
string abc;
if ((abc=getString()) != "")
{
MessageBox.Show(abc);
}

private string getString()
{
return "something";
}
=====
I get the MessageBox displayed. If I change != to == there's no MessageBox.

What is the != comparing, and how?

Nov 16 '05 #3
Daniel Billingsley <dbillingsley@NO_durcon_SPAAMM.com> wrote:
Or seem to anyway.
=====
string abc;
if ((abc=getString()) != "")
{
MessageBox.Show(abc);
}

private string getString()
{
return "something";
}
=====
I get the MessageBox displayed. If I change != to == there's no MessageBox.

What is the != comparing, and how?


It's comparing "" to the value of the expression (abc=getString())
which is the value of abc after the assignment, which is "something".
It's the same way that the common:

while ( (line=streamReader.ReadLine()) != null)

or

while ( (read=stream.Read(buffer, 0, buffer.Length)) > 0)

work.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 16 '05 #4
"Adam Clauss" <ca*****@tamu.edu> wrote in
news:es**************@TK2MSFTNGP10.phx.gbl:
"Daniel Billingsley" <dbillingsley@NO_durcon_SPAAMM.com> wrote in
message news:uq*************@TK2MSFTNGP11.phx.gbl...
Or seem to anyway.
=====
string abc;
if ((abc=getString()) != "")
{
MessageBox.Show(abc);
}


As your parenthesis indicate, the first thing that happens is:
(abc=getString())
so, abc gets the value of "something"

Which is then tested to be != to "", which is true. "something" != ""
so the messagebox shows. Why do you feel there it should be
otherwise?


Perhaps because the code reads:

If you assign the return value of getString() to abc and compare that
_operation_ to "" testing for inequality then...

(abc = getString()) has no return value and fails by throwing an exception
if something goes wrong; so, as the person asked, what is != comparing
with?

See my other reply for the answer.

Dave
Nov 16 '05 #5
"Daniel Billingsley" <dbillingsley@NO_durcon_SPAAMM.com> wrote in
news:uq*************@TK2MSFTNGP11.phx.gbl:
Or seem to anyway.
=====
string abc;
if ((abc=getString()) != "")
{
MessageBox.Show(abc);
}

private string getString()
{
return "something";
}
=====
I get the MessageBox displayed. If I change != to == there's no
MessageBox.

What is the != comparing, and how?


Interesting question. Let's see what the compiler is up to by using ILDASM
to look at the generated IL code. I've put the code in the click event of
a button.
..method private hidebysig instance void button1_Click(object sender,
class [mscorlib]
System.EventArgs e) cil managed
{
// Code size 32 (0x20)
.maxstack 2
.locals init ([0] string abc)

//push the this pointer onto the stack
IL_0000: ldarg.0
//Stack now looks like:
// this
//load the return value of getString onto the stack
IL_0001: call instance string WindowsApplication5.Form1::getString
()
//Stack now looks like:
// this, "Something"

//Copy the top most value on the stack
IL_0006: dup
//Stack now looks like:
// this, "Something", "Something"

//Store the topmost value on the stack to
//the first local variable (abc in this case)
IL_0007: stloc.0
//Stack now looks like:
// this, "Something"

//Load an empty string onto the stack
IL_0008: ldstr ""
//Stack now looks like:
// this, "Something", ""

//Test the top two values on the stack for
//Inequality
IL_000d: call bool [mscorlib]System.String::op_Inequality
string,string)
//Stack now looks like:
// this

//If False then jump to IL_001f
IL_0012: brfalse.s IL_001f

//Since the comparison of the top two stack values
//returns true you get the message box
//Load the string onto the stack
IL_0014: ldstr "Hello Something"
//Stack now looks like:
// this, "Hello Something"

//Show the message box
IL_0019: call valuetype [System.Windows.Forms]
System.Windows.Forms.DialogResult [System.Windows.Forms]
System.Windows.Forms.MessageBox::Show(string)
//Stack now looks like:
// this

//pop the this pointer off the stack
IL_001e: pop

//return
IL_001f: ret
} // end of method Form1::button1_Click

So, now you can see what is happening behind the scenes which should help
to explain what was going on in that expression and why it works.

Dave
Nov 16 '05 #6
> (abc = getString()) has no return value and fails by throwing an exception
if something goes wrong; so, as the person asked, what is != comparing
with?


What do you mean it has no return value... it most certainly does. Returns the value of the string assigned. The assignment
operator returns the value assigned (or reference, whatever you happen to be dealing with).
It is what allows:
string a = "a";
string b, c;
b = c = a;

Also, the same principle as something like this would work:
StreamReader sr = .....
string line;
while ( (line = sr.ReadLine()) != null)
{
....
}

If the assignment operator did not return a value, neither of the above would be possible.

--
Adam Clauss
ca*****@tamu.edu

Nov 16 '05 #7
"Adam Clauss" <ca*****@tamu.edu> wrote in
news:#H*************@TK2MSFTNGP12.phx.gbl:
(abc = getString()) has no return value and fails by throwing an
exception if something goes wrong; so, as the person asked, what is
!= comparing with?


What do you mean it has no return value... it most certainly does.
Returns the value of the string assigned. The assignment operator
returns the value assigned (or reference, whatever you happen to be
dealing with). It is what allows:
string a = "a";
string b, c;
b = c = a;

Also, the same principle as something like this would work:
StreamReader sr = .....
string line;
while ( (line = sr.ReadLine()) != null)
{
...
}

If the assignment operator did not return a value, neither of the
above would be possible.


Not the *operator*. The actual operation that's in parens.

(abc = getString()); is a stand alone operation. abc gets the value of
getString() but the code does not read:

abc = getString();
if(abc != "")

In the example, the left operand of the != operator is an expression.
There's no extra "=" operator as in your example so that something like
this would be obvious:

(a = (b = c) != "")

which is effectively the same as
b = c;
a = b;
a != "";

What we have is:

b = c;
? != "";


Nov 16 '05 #8
"David Totzke (.NET/C# MVP)" <da**********@gmail.com> wrote in message news:Xn*********************************@207.35.17 7.134...
"Adam Clauss" <ca*****@tamu.edu> wrote in
news:#H*************@TK2MSFTNGP12.phx.gbl:
What we have is:

b = c;
? != "";


Where in this case, by definition of the assignment operator ? IS abc.

--
Adam Clauss
ca*****@tamu.edu
Nov 16 '05 #9
David Totzke (.NET/C# MVP) <da**********@gmail.com> wrote:
Perhaps because the code reads:

If you assign the return value of getString() to abc and compare that
_operation_ to "" testing for inequality then...

(abc = getString()) has no return value and fails by throwing an exception
if something goes wrong; so, as the person asked, what is != comparing
with?


No, the expression (abc=getString()) *does* have a value (not a return
value, but a value).

From section 14.13.1 of the ECMA C# spec:

<quote>
http://www.pobox.com/~skeet/csharp/faq/#db.parameters
</quote>

That value is what != is comparing with.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 16 '05 #10
David Totzke (.NET/C# MVP) <da**********@gmail.com> wrote:
If the assignment operator did not return a value, neither of the
above would be possible.
Not the *operator*. The actual operation that's in parens.

(abc = getString()); is a stand alone operation. abc gets the value of
getString() but the code does not read:

abc = getString();
if(abc != "")


Although it doesn't read that way, it is semantically equivalent to
that.
In the example, the left operand of the != operator is an expression.


Yes, and the value of the expression is the value assigned to the left-
hand side of the assignment operator, as specified in the C# language
specification.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 16 '05 #11
Hi,
inline

"David Totzke (.NET/C# MVP)" <da**********@gmail.com> wrote in message
news:Xn*********************************@207.35.17 7.134...
"Adam Clauss" <ca*****@tamu.edu> wrote in
news:#H*************@TK2MSFTNGP12.phx.gbl:
(abc = getString()) has no return value and fails by throwing an
exception if something goes wrong; so, as the person asked, what is
!= comparing with?
What do you mean it has no return value... it most certainly does.
Returns the value of the string assigned. The assignment operator
returns the value assigned (or reference, whatever you happen to be
dealing with). It is what allows:
string a = "a";
string b, c;
b = c = a;

Also, the same principle as something like this would work:
StreamReader sr = .....
string line;
while ( (line = sr.ReadLine()) != null)
{
...
}

If the assignment operator did not return a value, neither of the
above would be possible.


Not the *operator*. The actual operation that's in parens.

(abc = getString()); is a stand alone operation. abc gets the value of
getString() but the code does not read:

abc = getString();
if(abc != "")

In the example, the left operand of the != operator is an expression.
There's no extra "=" operator as in your example so that something like
this would be obvious:

(a = (b = c) != "")

which is effectively the same as
b = c;
a = b;
a != "";


No, it's not.

(a = (b = c) != "") doesn't compile, and it's effectively the same as:

b = c;
a = (b!=""); // ERROR, assigning bool to string


What we have is:

b = c;
? != "";
Wrong. (b=c) has the value of b after c is assigned to it.
Greetings



Nov 16 '05 #12
Thanks Jon, that's exactly what I was looking for.

"Jon Skeet [C# MVP]" <sk***@pobox.com> wrote in message
news:MP************************@msnews.microsoft.c om...

Yes, and the value of the expression is the value assigned to the left-
hand side of the assignment operator, as specified in the C# language
specification.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too

Nov 16 '05 #13
Jon Skeet [C# MVP] <sk***@pobox.com> wrote in
news:MP************************@msnews.microsoft.c om:
Yes, and the value of the expression is the value assigned to the left-
hand side of the assignment operator, as specified in the C# language
specification.


The original responses to the question were basically things like this:
"What did you expect?"

I took a shot and showed under the covers why it does work. Not being one
for reading specs the statement's functionality does seem counter
intuitive. The spec makes it plain. Your answer now is a good one and
I've learned something from the exercise.

Someone pointed out one of the flaws in my analysis in that
(a = (b = c) != "") doesn't compile because (b = c) evaluates to a bool and
we get the old implicit type conversion error. So my next question would
be:

Why does...oh CRAP! I just saw my mistake. It's trying to assign the
value of (b = c) != "" to a. A bool and a string.

I originally went astray because I know that at some point I have hosed
myself by using the assignment operator in an if condition instead of the
comparison and it was never false because the assignment always worked.
This if(b = c){} won't compile in C# but I know I did it somewhere. Nearly
went insane until I spotted it. C++ maybe? Can anybody tell me?

Thanks for the help.

Cheers,
Dave
Nov 16 '05 #14
David Totzke (.NET/C# MVP) <da**********@gmail.com> wrote:
This if(b = c){} won't compile in C# but I know I did it somewhere. Nearly
went insane until I spotted it. C++ maybe? Can anybody tell me?


Yes, that works in C/C++, which is why you often see people writing

if (5==x)

instead of

if (x==5)

in case you make a typo and turn it into an assignment instead of a
comparison. In C# this is not needed (unless you're comparing boolean
constants, and there I usually just write if(x) or if(!x)) and makes
the code less readable, IMO.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 16 '05 #15
Hi,
<snip>
I originally went astray because I know that at some point I have hosed
myself by using the assignment operator in an if condition instead of the
comparison and it was never false because the assignment always worked.
This if(b = c){} won't compile in C# but I know I did it somewhere. Nearly went insane until I spotted it. C++ maybe? Can anybody tell me?
Yes, this may compile in c++, but it has the same effect as in c#. The
difference is that C# won't do an implicit cast.

<Quote from C++ iso standard 5.17>
There are serveral assignment operators, all of which group right-to-left.
All require a modifiable lvalue as their left operand and the type of an
assignment expression is that of its left operand. The result of assignment
is the value stored in the left operand after the assignment has taken
place; the result is an lvalue.
</Quote>

<Quote from C++ iso standard 6.4>
The value of a condition that is an expression is the value of the
expression, implicitly converted to bool ...
</Quote>

Rules for casting a number to bool are (true!=0,false=0).

int b;
if ( b = 5 )
{
// true, not because assignment succeeds, but because (b=5) is 5 which
is != 0
}

HTH,
greetings


Thanks for the help.

Cheers,
Dave

Nov 16 '05 #16
On Thu, 29 Jul 2004 13:49:45 +0100, Jon Skeet [C# MVP]
<sk***@pobox.com> wrote:
David Totzke (.NET/C# MVP) <da**********@gmail.com> wrote:
This if(b = c){} won't compile in C# but I know I did it somewhere. Nearly
went insane until I spotted it. C++ maybe? Can anybody tell me?


Yes, that works in C/C++, which is why you often see people writing

if (5==x)

instead of

if (x==5)


Jon,
Actually you won't see this often. It is considered by C programers
as a juvenile coding practice used by people that don't proof read
their own code.

Oz
--
A: Because it fouls the order in which people normally read text.
Q: Why is top-posting such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
Nov 16 '05 #17
ozbear <oz****@bigpond.com> wrote:
Yes, that works in C/C++, which is why you often see people writing

if (5==x)

instead of

if (x==5)
Actually you won't see this often. It is considered by C programers
as a juvenile coding practice used by people that don't proof read
their own code.


Well, I'm sure it's considered juvenile by some people, but definitely
not by others - and I've seen it reasonably often in C# code (where
it's useless in most cases)...

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 16 '05 #18
On Fri, 30 Jul 2004 14:04:52 +0100, Jon Skeet [C# MVP]
<sk***@pobox.com> wrote:
ozbear <oz****@bigpond.com> wrote:
>Yes, that works in C/C++, which is why you often see people writing
>
>if (5==x)
>
>instead of
>
>if (x==5)

Actually you won't see this often. It is considered by C programers
as a juvenile coding practice used by people that don't proof read
their own code.


Well, I'm sure it's considered juvenile by some people, but definitely
not by others - and I've seen it reasonably often in C# code (where
it's useless in most cases)...


Exactly my point (the useless comment). The "often" comment of
mine was with regards to C programmers, not C# programmers BTW.

And I've never seen it in used in any MSDN example.

BTW...thanks for the great article on threading. I don't know how
you find the time but I am glad you do/did!

Oz
--
A: Because it fouls the order in which people normally read text.
Q: Why is top-posting such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
Nov 16 '05 #19

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

7
by: Jonas | last post by:
This works fine in Win XP but does not work at all in Win 98. Private WithEvents objIExplorer As InternetExplorer I have to do it like this to get it to work in Win 98 Dim objIExplorer As...
2
by: Paul THompson | last post by:
I have a piece of code something like the following: START OF CODE <html><head><title>The Wizard</title></head> <body> <h1>Welcome to Joe's Vet Clinic</h1> <div id="part1"...
162
by: Isaac Grover | last post by:
Hi everyone, Just out of curiosity I recently pointed one of my hand-typed pages at the W3 Validator, and my hand-typed code was just ripped to shreds. Then I pointed some major sites...
5
by: me | last post by:
I have a Class Library that contains a Form and several helper classes. A thread gets created that performs processing of data behind the scenes and the Form never gets displayed (it is for debug...
4
by: rick | last post by:
The following basic script works fine in firefox by not in IE. Can anyone spot the problem? In IE I can only delete the first line but not the lines created by javascript. Also, look at the HTML...
6
by: benb | last post by:
I have form that looks a lot like a search bar for the user to search for records matching specified criteria (e.g. first names containing "ben"). For robust results, an intermediary form displays...
14
by: Anoop | last post by:
Hi, I am new to this newsgroup and need help in the following questions. 1. I am workin' on a GUI application. Does C# provides Layout Managers the way Java does to design GUI? I know that it...
89
by: Cuthbert | last post by:
After compiling the source code with gcc v.4.1.1, I got a warning message: "/tmp/ccixzSIL.o: In function 'main';ex.c: (.text+0x9a): warning: the 'gets' function is dangerous and should not be...
14
by: webEater | last post by:
I have a problem, it's not browser specific, and I don't get a solution. I have an (X)HTML document, I show you a part of it: .... <!--<div class="pad">--> <div id="eventImages"><img src=""...
1
by: =?ISO-8859-1?Q?Lasse_V=E5gs=E6ther_Karlsen?= | last post by:
I get the above error in some of the ASP.NET web applications on a server, and I need some help figuring out how to deal with it. This is a rather long post, and I hope I have enough details that...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.