Convert increment value - c#

I tried to convert incremented value to string.
i++.ToString()
The above statement working fine.
++i.ToString()
This one showing error line. Why?

Because in the second expression the ToString() method of i is called first and the ++ operator is meaningless for strings. On the other hand, in your first expression, the integer i is get incremented by one and the method ToString() is called. So you get the string representation of your number. You could conver it, as already ulugbek-umirov pointed out in his comment:
(++i).ToString();
Please have a look here.

It is caused by the different operator precendence of i++ and ++i.
i++ belongs to "Primary" whereas ++i belongs to the "Unary" group. But since the . belongs also to "Primary" is has a higher precendence . So .ToString is executed first. You cannot use ++ operator on a string.
You can wrap it in paranthesis:
(++i).ToString()
Reference: Operators

Because the second means:
++(i.ToString()) // Oops, compiler error
and string type can not be incremented.

(++i).ToString() will do the trick.

The error is caused by the precedence of the operators being applied.
In your instruction you're trying to apply an int-increment to a string.
If you want to post increment you should do:
(++i).ToString();

Answers and comments saying that this is due to anything "executing first" are misleading. This problem is due to the higher precedence of . relative to ++(prefix). Order of evaluation has nothing to do with it really - especially since ++i.ToString() does not compile and therefore there is no evaluation at all (hence no order in which it happens).
See also precedence vs associativity vs order.

You have to options
make it in 2 times:
i++;
i.ToString();
Use parenthesis to set priority (first increase then convert to string)
(++i).ToString();
or
(i++).ToString();

Because when ++ is used as a postfix, it will increase its value immediately then covert it to string using ToString();
Instead if you use ++ as prefix operator then it will convert the existing value to string using ToString() then it will try to increment the value, so in this case you are getting error on increment a string value...
so try using parenthesis for increasing its precedence as (++i).ToString();

Related

C# how to get value from specific cell datagridview

i am working on C# and trying to save my datagridview to xml.
my code as follow :
writer.WriteStartElement("NamaBarang");
writer.WriteString(dgvCart.Rows[i].Cells[1].Value.ToString);
writer.WriteEndElement();
and the error occur at
writer.WriteString(dgvCart.Rows[i].Cells[1].Value.ToString);
Error 2 The best overloaded method match for
'System.Xml.XmlWriter.WriteString(string)' has some invalid
arguments C:\Users\Eric\Desktop\C#\Gridview\Gridview\Form1.cs 59 25 Gridview
and
Error 3 Argument 1: cannot convert from 'method group' to
'string' C:\Users\Eric\Desktop\C#\Gridview\Gridview\Form1.cs 59 44 Gridview
i am previously a vb user so i am having a hard time in c#
please help.
Youve forgotten to put empty brackets () after your ToString
VB isn't bothered about this but c# is- every time you want to call a method that has no arguments, you have to put empty brackets
//this is fine in VB
Dim x as String = y.ToString
//so is this
Dim x as String = y.ToString()
//in c# we insist on brackets when calling a method
string x = y.ToString();
//no brackets means "get the value of the property"
int I = mystring.Length;
Seeing something that looks like a method name, without brackets, usually means it's a property rather than a method. It can occasionally mean that the method itself is being used as an argument - a way of passing a method around as a variable, but that's beyond the scope of what we're discussing here.. Read up on delegates if you're interested.
In short, if you want to call a method in c#, it absolutely must have brackets after the name, whether there are arguments or not
Also handy to remember that when you see the error about "is a method group" it probably means you've tried to call a method but omitted the brackets.
C# is a struggle for VB people because it's essentially way more demanding that the syntax be absolutely right- you'll get used to it though, and it does help eventually!

Cannot interpret token '!' at position 5

I have a column named 'Jul' which contains some values like '123' and '-'. I'm trying to get sum of column by adding values and neglecting '-'. I tried:
object julysum;
julysum = Convert.ToDouble(FormattedPurchaseSummaryTable.Compute("SUM(Jul)", "Jul != '-'"));
but i'm getting error: Cannot interpret token '!' at position 5.
How can i resolve this error?
There is no != operator.
You likely want <>.
Please read here for more information on what operators are available: https://learn.microsoft.com/en-us/dotnet/api/system.data.datacolumn.expression?redirectedfrom=MSDN&view=netframework-4.7.2#operators
Blam's answer already pointed you towards the expression language. Having fixed the first issue, we need to fix the second which is that Jul is a string, not an integer (or float, etc). So we need to convert it as well.
But, per Compute I don't think it'll support a complex expression within the SUM to do the CONVERT.
So I think what you need to do is to add a new DataColumn with an expression something like:
IIF(Jul != '-',CONVERT(Jul,'System.Int32'),0)
And then compute your SUM over this new column instead.

How to initialize default value to C#7 out variables?

I used TryParse to parse a string to number. I need a solution to initialize out variable with default value, So when TryParse fails to convert I get my default value.
Here is the code :
long.TryParse(input.Code, out long Code = 123);
//Error CS1525 Invalid expression term '='
I want to strictly to use C#7 out variables standard.
Whilst the out parameter itself cannot take a default value, you can achieve what you want to do with a single expression in C# 7. You simply combine the out parameter with a ternary expression:
var code = long.TryParse(input.Code, out long result) ? result : 123;
You can't do it... The .NET runtime doesn't know anything of "success" or "failure" of long.TryParse. It only knows that TryParse has a bool return value and that after TryParse finishes, the out variable will be initialized. There is no necessary correlation between true and "there is a good value in result" and false and "there is no good value in result".
To make it clear, you could have:
static bool NotTryParse(string s, out long result)
{
return !long.TryParse(s, out result);
}
And now? When should your default value be used?

Why this exception occured?

I have a dictionary name Pair in c#. It contains some key - value pairs. I added a screen shot, there was an exception generated on (p.Key == "left), Sequence containes no matching element but if you see in the Pair Dictionary, the left key is present there. Then please anybody tell me why this exception occured ?
If I can see it right, the left value is preceded with a whitespace, " left", so p.Key == "left" is never true.
Use p.Key.contains("left") instead, or check if it returns a value or not, before trying to manipulate it. Or trim the leading and trailing whitespaces.
If it isnt a white-soace issue, then the only way I can that happening is if the dictionary is a Dictionary<object,...>, in which case the == you are using is reference equality, not string equality. That would cause it to fail. If so, either use a Dictionary<string,...> or use Equals("left", p,Key).
Note that Pair["left"] would be a much better way of doing the lookup.
You should use indexer or TryGetValue instead of Single. With Single, there is no reason to use dictionary.
Also, your problem stems from the fact, that there is space before the 'left' so the whole string is actually " left". See how width is one character to the left.

What is wrong with ToLowerInvariant()?

I have the following line of code:
var connectionString = configItems.
Find(item => item.Name.ToLowerInvariant() == "connectionstring");
VS 2010 code analysis is telling me the following:
Warning 7 CA1308 : Microsoft.Globalization : In method ... replace the call to 'string.ToLowerInvariant()' with String.ToUpperInvariant().
Does this mean ToUpperInvariant() is more reliable?
Google gives a hint pointing to CA1308: Normalize strings to uppercase
It says:
Strings should be normalized to uppercase. A small group of characters, when they are converted to lowercase, cannot make a round trip. To make a round trip means to convert the characters from one locale to another locale that represents character data differently, and then to accurately retrieve the original characters from the converted characters.
So, yes - ToUpper is more reliable than ToLower.
In the future I suggest googling first - I do that for all those FxCop warnings I get thrown around ;) Helps a lot to read the corresponding documentation ;)
Besides what TomTom says, .net is optimized for string comparison in upper case. So using upper invariant is theoretically faster than lowerinvariant.
This is indeed stated in CLR via C# as pointed out in the comments.
Im not sure if this is of course really true since there is nothing to be found on MSDN about this topic. The string comparison guide on msdn mentions that toupperinvariant and tolowerinvariant are equal and does not prefer the former.

Categories