I want to do a checking on a textbox, if null then assign zero, after that proceed with some calculation. I know there is a null coalescing (??) operator can help me, but I'm not sure is it possible for me to assign int when textbox is empty.
I tried to write something like this, but seems like is an error.
sdowntime = Convert.ToInt32(txtSDown.Text) ?? 0;
I get this
Error 98 Operator '??' cannot be applied to operands of type 'int' and 'int'
Anything I made it wrong or actually I should use another method? Please guide.
Thank you very much!
You could also use the TryParse method, like so:
int sdowntime;
int.TryParse(txtSDown.Text, out sdowntime);
If the TextBox is blank or contains a non-numeric value, the out parameter will be assigned the value 0. Otherwise, the appropriately parsed value is assigned. Please note, however, that you should always have client-side validation to ensure that non-numeric values are not entered by users in numeric fields.
You get the error because int is a value type. And since value types are not null-able, it is meaningless to use null-coalescing operator on them.
What you really need to do is check the null-ness of the text:
string textToParse = txtDown.Text ?? "0";
Edit: So I made a mistake and it has been pointed out that TextBox.Text can never be null.
Extra:
Even if you check for null, Convert.ToInt32 can fail if your text is not null, but empty ("" or String.Empty). You can use int.TryParse.
int sdowntime;
if (!int.TryParse(txtDown.Text ?? "0", out sdowntime))
{
// int.TryParse will assign 0 to sdowntime if it fails
// so watch out for that too.
}
Related
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?
So let's say you have a string and you want to check for null/empty. You also want to check for empty string. The only way I know how to do this (below) is to first check for null AND THEN check for empty string. If you do the .Trim() before checking for null, and there is a null, then you have an error.
I really don't like having to use two separate If Statements. Is there a way around this?
Example:
if(!string.IsNullOrEmpty(strMyVariable)
{
if(!string.IsNullOrEmpty(strMyVariable.Trim()))
{
//the variable is not null, empty, or contain an empty string
//so you can now (finally!) do something with it.
}
}
You can use:
string.IsNullOrWhiteSpace
https://msdn.microsoft.com/en-us/library/system.string.isnullorwhitespace(v=vs.110).aspx
You can use IsNullOrWhiteSpace like this:
if (!string.IsNullOrWhiteSpace(strMyVariable))
{
}
Quoting from the MSDN reference:
Indicates whether a specified string is null, empty, or consists only of white-space characters.
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();
How do I check the empty check boxes which convert strings to integers using "int.Parse" in C#?
If I try to pass blank text boxes, visual studio gives me this error - "Input string was not in a correct format."
I already read some questions on stackoverflow which address the same issue, but I know that various people use various methods to do the same task. So I would like to know them as well. Please start with the simplest way you know first.
int multiplyBy;
if(int.TryParse(textBox3.Text, out multiplyBy)) {
//success
} else {
//string was not in correct format
}
The int.TryParse(string s, out int result) method trys to parse the string, but throws no exception if the format is wrong, it returns a bool indicating if the format was valid. The out int result parameter is the int wich should get the value.
Use Int32.TryParse to verify that the value in the text box is a valid integer
http://msdn.microsoft.com/en-us/library/f02979c7.aspx
You can check if the textbox has a value with:
string.IsNullOrEmpty(textbox.Text)
if you want it in single line of code
vb.net
int i = If(String.IsNullOrEmpty(TextBox1.Text), 0, Int32.Parse(TextBox1.Text))
c#
int i = (String.IsNullOrEmpty(TextBox1.Text)) ?? 0: Int32.Parse(TextBox1.Text)
Instead of directly parsing string representation into integer, check whether it is able to convert in integer. .NET has TryParse method of integer which tries to convert the string representation into int , and returns the bool value indicates whether the conversion succeeded. And if succeeded, stores the parsed value in second parameter of TryParse function which is of out type.
Note: TryParse method does not throw an exception if the conversion fails. It simply returns false indicates that conversion is got failed.
Ref : http://msdn.microsoft.com/en-us/library/f02979c7.aspx
Why don't you just catch the exception
try
{
int multiplyBy = int.Parse(textBox3.Text);
} catch(Exception){}
You can also catch(FormateException) if you like.
Hope this helps!
I found this article on the webs and thought I'd try to apply the null string style method to my excel range value. Sometimes it has a value in it and sometimes it doesn't and obviously double doesn't like null values.
This is my little snippet.
double valTotal = (rngTotal.Value != null ? 1 : 0);
My question is what am I doing with this above code? It looks like an if statement in one line with the "1" being the "then" and the "0" being the "else". Is that right? And most importantly, what is the name of this syntax so I can find out more about this?
It's the conditional operator. (Sometimes incorrectly called the ternary operator; it's a ternary operator as it has three operands, but its name is the conditional operator. If another ternary operator is ever added to C#, "the ternary operator" will become an ambiguous/non-sensical phrase.)
Quick description:
The first operand is evaluated, and if the result is true, the second operand is evaluated and forms the overall value of the expression. Otherwise the third operand is evaluated and forms the overall value of the expression.
There's a little more detail to it in terms of type conversions etc, but that's the basic gist.
Importantly, the first operand is always evaluated exactly once, and only one of the second or third operand is evaluated. So for example, this is always safe:
string text = GetValueOrNull();
int length = text == null ? 5 : text.Length;
That can never throw a NullReferenceException as text.Length isn't evaluated if text == null is true.
It's also important that it's a single expression - that means you can use it in some places (such as variable initializers) where you couldn't use the if/else equivalent.
Closely related is the null-coalescing operator which is also worth knowing about.
It's the conditional operator:
http://msdn.microsoft.com/en-us/library/ty67wk28(v=vs.80).aspx
This is known as the conditional / ternary operator in C#. It's essentially short hand for the following
double valTotal;
if (rngTotal.Value !=null) {
valTotal = 1;
} else {
valTotal = 0;
}
It is the conditional operator. Yes, it acts like an "inline if". It is a handy shortcut for short if expressions. The part before the '?' is a Boolean condition if the Boolean condition is true then the part after the '?' is evaluated otherwise the part after the ':' is evaluated. In other words the '?' and ':' act like the 'then' and 'else' in an if statement.
See the links below for more detail.
https://msdn.microsoft.com/en-us/library/ty67wk28.aspx
The ternary (conditional) operator in C
It's called conditional operator:
http://msdn.microsoft.com/en-us/library/ty67wk28(v=vs.80).aspx