This question already has answers here:
Equivalent of Visual Basic's And and Or in C#?
(6 answers)
Closed 7 years ago.
I'm trying to translate a certain code to c#.
Basically I understand most of the code I'm dealing with, and even the intent of the original code.
but I wanna be sure I have all my bases covered.
its the 5th post in this topic: http://www.pcreview.co.uk/threads/how-to-use-getwindowlong-properly-in-vb-net.1312789/
by user Kresimir
the code at question:
Dim ret As Integer = User32DLL.GetWindowLong(Me.Handle, -16)
Dim s As String = String.Empty
If (ret And WS_BORDER) Then s &= "WS_BORDER" & NewLine
I do not understand what the "If (ret And WS_BORDER)" statement is supposed to do, and how to translate it to C#
is it:
if (ret!=null & WS_BORDER!=null)
or something else?
Thank you.
edit: note. If I use the above mentioned C# statement, VS gives me a notice that "the result of the expression is always false since a value of type "int" is never equal to "null" of type "int?"
^I guess I can neglect it(googling it as we speak), but if sm1 wishes to give me a "free of charge explanation" I'd appreciate it :*
ps. I'm really a newb to this, so I'm sorry if I overlooked something obvious.
None of the previous answers are right:
if((ret & WS_BORDER) != 0)
This is a check to see if a variable contains a flag, in this case WS_BORDER.
This is a bitwise logic operation. When Visual Basic converts numeric data type values to Boolean, 0 becomes False and all other values become True. So if the statement is not 0:
User32DLL.GetWindowLong(Me.Handle, -16)
...and WS_BORDER is not falsy the result will be true. If either are false, the result will be false.
Related
I have seen many colleagues by mistake use
x is true
to check if the variable is true.
Independently of whether it is necessary to use is or the correct == to check if a boolean is true, I'd like to understand why this is not a compilation error.
The documentation1 2 of is states:
The is operator checks if the result of an expression is compatible with a given type.
AFAIK true is not a type.
Interestingly this also works for integers.
Update:
I tried it out with the online editor provided by W3 and there it used to be an error. Has pattern matching changed this behaviour with C# 8?
So does x is true do the same as x == true in C# 8 (even without the {}?
This question already has answers here:
compare two string value [closed]
(6 answers)
Closed 3 years ago.
I'm a beginner in c# and I'm making a console guess the number game. You enter a number and it tells you to guess higher or lower or if you guessed the number. Anyways, I'm having trouble comparing the answer with the users guess.
I've tried comparing string guess with string answer using a <= in an if statement. I got an error that says "Operator '<=' cannot be applied to operands of 'string' and'string'.
The code:
string answer = "537";
string guess = Console.ReadLine();
*if (guess <= answer)*
The code with asterisks is the code I'm getting an error from. Does anyone know what I'm doing wrong and a solution?
Since you've said that you're a beginner,
<= isn't valid for strings.
Imagine if I did this:
string foo = "Hello world";
string bar = "Wassup?"
if(foo <= bar)
{
/// do something
}
What, exactly, would foo <= bar mean in that context? We could trying to compare the length of the strings (bar is shorter than foo), the sum of the ASCII values of the characters in each string, or just about anything. It's possible to implement methods that do those things, but none of them make sense in the general case so the language doesn't try, and it shouldn't.
The difference between a string and an int is that the former is intended to contain character data, like a name or a sentence. Mathematical comparisons like <= apply to numeric data, like integers and floating point values. So, to get the behavior you're looking for, you need to convert your text data into a numeric type.
The nature of data types and how they are stored, comparisons, etc. is a nontrivial discussion. But, suffice it to say that the string "123" is NOT the same as the number (integer, most likely) 123.
The easiest fix for your code would be something like:
string answer = "537";
string guess = Console.ReadLine();
var intAnswer = Int32.Parse(answer);
var intGuess = Int32.Parse(guess);
if (intGuess <= intAnswer)
{
/// do something...
}
Note that this will throw an exception if the user enters anything in the console that is not a valid digit. (Look up TryParse for a better solution, but that's beyond the scope of this answer and I think it'll just confuse the issue in this case.)
I'd spend some time reading about data types, int vs string, etc. This is a reasonable question about something that is not obvious to those just getting started.
Keep at it. We all started somewhere, and this is as good a place as any.
strings cannot be treated as number, it will only compare if they are equal. if numbers are the input. convert it to int first, both the guess and answer. if the guess will always be a number this would suffice.
if (Convert.ToInt32(guess) <= Convert.ToInt32(answer))
{
}
if not try to do a try catch or Int32.TryParse
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
Reading a job ad, a requirement (sigh) was that the applicant should more or less hate the usage of variable !== FALSE. I, however, cannot see the reason of this, since I find it quite handy.
Say that a function (get_user( int user_id )) returns FALSE if it doesn't succeed (find the requested user), I can simply use:
user = get_user(823);
if(user !== FALSE) {
// User found
} else {
// No user found
}
I could, of course, simply use if(!user), however, I don't always find it suiting, especially when I have a few conditions to meet.
Are there any disadventages of writing code like this?
Clarification: This is a more global question, as the ad were against PHP usage of !== FALSE and C# usage of != FALSE.
You say get_user returns false when it doesn't succeed - and that's most of the problem. If a function call does not succeed, it should throw an exception, not return an answer that is not type safe ("false" as opposed to a User).
You could do on accident
if($variable = FALSE)
And this would change the value of $variable
In Javascript, the two following are equivalents:
user != FALSE
!user
However, this is slightly different:
user !== FALSE
as it is the negation of ===, which checks for both values and types to be the same.
Reference:
http://www.w3schools.com/js/js_comparisons.asp
If you have in Java
Boolean flag1 = new Boolean(true);
Boolean flag2 = new Boolean(false);
if (flag1 == Boolean.TRUE || flag1 == Boolean.FALSE) // is false.
if (flag2 == Boolean.TRUE || flag2 == Boolean.FALSE) // is false.
if (flag1 != Boolean.FALSE && flag2 != Boolean.FALSE) // is true
Using == FALSE or != FALSE may not work the way you think so while it is more verbose, it is also error prone.
From a dev point of view, it's better to design your methods that do not return different values that evaluate to FALSE. Eg your function should not return multiple possible values of 0 or NULL or FALSE or "" (empty string) or empty array() because this would require some unobvious logic to check the result after.
If we talk about PHP on the other hand it's good to know that some functions return both zero or false, eg strpos. You should not assume if (!strpos(...)) means the string is not contained in the other string, it could be on zero position, which evaluates to FALSE. Sometimes also a function might return FALSE on failure or empty array on success (that did not produce result that evaluates to TRUE).
So, point out there are cases this is neccessary or useful, but in general its bad practice to return multiple values that evaluate to FALSE, thus requiring to include the type in the comparisment operator.
What is asked for a requirement might be related to taste and to field of use.
In a strict logical system, one might be inclined to select ID values that represent objects (in any kind of store or memory) to not be 0 (and to be positive numbers only).
That leaves room for having 0 to represent a non-existing object (so called NULL object).
Also negative numbers could be used to signal meta information like errors. But a strict system should not use any negative numbers and pass meta-information on some context instead of the mainline of data-flow.
Probably this is what is wanted. In that case the value FALSE would not exist, because the whole system is about numbers only.
The benefit of such a system is that it works nearly in every programming language and across different paradigms.
Also commonly the number zero expresses a falsy condition, and non-zero numbers a truthy one.
Actually it depends on the language.
C
In the programm language C there is no bool and then TRUE or FALSE are defined values, mostly 1 for TRUE and 0 for FALSE. However, since this is just a sort of convention, some define FALSE as -1 and TRUE as 255. You see this results in strange behavior, therefor in C always check against a defined value and make sure those values match.
Also in C some people think the best way is to use 'FALSE == a' instead of 'a == FALSE'. The reason is that if one = is forgotten, the first (FALSE == a) gives a compilation error, and the second is treated as an assignment, which clearly is unintended.
C#
However, in C#, true and false are predefined and checking a variable against true and false is quite useless. a == true means exactly the same as just writing a.
Python
In Python however, there is a change. a == true means that the variable a should be a boolean, if you write just 'a' then it means it can also be 0, [], {} or any inited value.
A bit off-topic: I think if such detail is part of a 'requirement for a job', the job requirements would be like 10,000 pages.
I have noticed that the immediate window in VS 2010 behaves differently when debugging a C# project and a VB.NET project, although I haven't been able to find any specific documentation of this difference.
For C# projects, I can simply type in any expression, and it will be evaluated and displayed, i.e. typing in
foo.bar == "baz"
will output
false
In VB.NET, however, doing the same thing outputs nothing.
I have to put a question mark in front of the expression for it to work.
?foo.bar = "baz"
false
Edit for clarity and my bad example above:
All other expressions exhibit the same behavior, including simple math such as '1 + 2'. Sometimes the error message is different though, as 1 + 2 results in the error 'Labels that are numbers must be followed by colons.'
Is there a way to 'fix' this behavior and make the VB.NET immediate window behave more like the C# one? Having to type a ? in front of every statement can be a pain when using it frequently.
The semantics of the immediate windows are just different. In C#, any expression or statement you enter is evaluated, and the result of the evaluation is printed to the window. In VB.NET, you have to enter a complete statement; you can't enter a bare expression. In your example, as you discovered, you need to use the 'Print' statement (the alias for which is ?) if you want to print anything to the window.
One reason for this is that the semantics of the languages are different. As Bob Kaufman mentioned, = can be an assignment operator or an equality test. If the VB.NET window worked like the c# window, there would be no way to determine whether a = b meant "assign b to a" or "evaluate whether b is equal to a".
Assignments do not have a value in VB.NET; a = b = 4 means "evaluate whether b is equal to 4, and assign the result of that evaluation to a." This means that a will either be equal to true or false.
In C#, an assigment is also an expression with a value, so a = b = 4 means "assign the value 4 to b, and assign the value of the expression (b = 4) to a." This means that a will be equal to 4.
The immediate window parser expects a statement if you don't use the ? command. The command
foo.bar = "baz"
is legal in vb.net, it is an assignment statement, giving the bar field or property of the object foo the value "baz". It is however going to complain if bar is a method of the class. Similarly, "1+2" is not a valid statement in vb.net, the ? command helps the interpreter to understand that you meant to evaluate an expression. To turn the = operator from an assignment into a comparison operator, you have to make the parser understand that an expression is being evaluated. ? required. Same thing for "1+2", the vb.net statement parser accepts a number at the start of a statement as a statement label, fit for a GoTo.
The C# language follows the curly brace languages standard where any expression is also a valid statement. So "1+2" is interpreted as a valid statement without help from ? Which is also the reason it needs a separate symbol for the equality operator (==), a parser wouldn't otherwise know the difference between an assignment statement and an expression.
Recently in a previous project I came across a peculiar difference between VB.NET and C#.
Consider the following C# expression which:
null <= 2
This expression evaluates to False which is what I would expect.
Then the corresponding VB.NET expression:
Nothing <= 2
I was surprised to learn that this expression actually evaluates to True
It seems like a fairly fundamental design decision between the two languages and it certainly caught me out.
Is anyone able to tell me why?
Are null and Nothing one and the same?
If so, why do they behave differently?
Nothing in VB evaluates to the default value for a given type. (See this link for details.)
For an integer comparison (which the compiler will assume from the right hand operand), Nothing will thus be 0. 0 <= 2 is true for more obvious reasons :-)