It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 9 years ago.
When I remove the ToString() in the method below, I get no error, so why is it necessary?
public string BuildEquation()
{
switch (Choice)
{
case "A":
return mNumber1.ToString() + "+" + mNumber2.ToString();
case "S":
return mNumber1.ToString() + "-" + mNumber2.ToString();
case "M":
return mNumber1.ToString() + "*" + mNumber2.ToString();
default:
return mNumber1.ToString() + "/" + mNumber2.ToString(); // corrected
}
}
From the C# Language Specification 1.2, §7.7.4, Addition operator:
String concatenation: The binary + operator performs string
concatenation when one or both operands are of type string. If an
operand of string concatenation is null, an empty string is
substituted. Otherwise, any non-string argument is converted to its
string representation by invoking the virtual ToString method
inherited from type object. If ToString returns null, an empty string
is substituted. [...] A System.OutOfMemoryException may be thrown if
there is not enough memory available to allocate the resulting
string.
In other words, the + operand will do the ToString conversion for you.
so why is it necessary?
It's not necessary.
Some people may subjectively consider it more readable to include it, but omitting it not only doesn't result in any errors, but it also produces the exact same output. There is no functional change in omitting the ToString calls.
Concatening double and string together converts it for you.
Otherwise you can convert it with .ToString()
Or use Convert.ToString(double) method. http://msdn.microsoft.com/en-us/library/c309e6c9.aspx
It's because you are concatenating with a string already ("+", "-", etc), which means the rest of the expression is resolved to a string type. If you didn't concatenate those extra strings, then you would need to call ToString().
Related
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 9 years ago.
I have a problem in my windows form in c#. The program is simple;
there are 3 textboxes and then it sums their values. however, when i click on the sum button without entering any values in the other 3 textboxes, the program crashes.
How can i make these textboxes accept only positive numbers and zeros?
this is what i did
private void button1_Click(object sender, EventArgs e)
{
double FirstNumb = Convert.ToDouble(txtFirstValue.Text);
double SecondNumb = Convert.ToDouble(txtSecondValue.Text);
double ThirdNumb = Convert.ToDouble(txtThirdValue.Text);
double m;
m = FirstNumb + SecondNumb + ThirdNumb;
listBox1.Items.Add(m);
}
Try to resolve using int.TryParse. This handles string as well.
Demo Reference
You are likely trying to convert the textboxes textual content to int. Unfortunately, you cannot convert an empty string to a number. Try setting the textboxes default content to "0".
You'll want to check that the string value from the text box is not null or empty, or otherwise invalid. Change this line:
double FirstNumb = Convert.ToDouble(txtFirstValue.Text);
to this
double FirstNumb = 0;
double.TryParse(txtFirstValue.Text, out FirstNumb);
FirstNumb will remain 0 if the parsing fails. Note that TryParse returns a bool, true if the parsing was successful and false otherwise. You can also take action on that as well, perhaps showing a MessageBox asking the user to fill a value and exiting the summation method.
See the documentation for more information: http://msdn.microsoft.com/en-us/library/994c0zb1(v=vs.100).aspx
EDIT: If you want to enforce only positive values, after the try parse you'll have to check that FirstNumb >= 0 and use a MessageBox to alert the user why, and abort the summation method.
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 9 years ago.
I Have this clausule
if ((line.Contains('%')) || (line.Contains('#')) || (line.Contains("") && (!line.Contains(','))))
and i want rewrite it to one method,beacause this is too slow. Any ideas??
if(line.Intersect("%#,").Any())
or
if("%#,".Intersect(line).Any())
(Reversing the parameters may improve performance, depending on the type of data in line and the percentage of characters that match.)
Both the other answers seem to ignore the fact that the original code returns true when line contains % or # or when it does NOT contain ,. (the empty string being totally irrelevant).
The correct way to write this would be:
if(line.Intersect("%#").Any() || !line.Contains(","))
Or possibly:
char[] includes = { '%', '#' };
char[] excludes = { ',' };
if(line.Intersect(includes).Any() || !line.Intersect(excludes).Any())
Or this:
char[] includes = { '%', '#' };
char[] excludes = { ',' };
if(line.IndexOfAny(includes) != -1 || line.IndexOfAny(excludes) == -1)
First, lets simplify the whole statement. You use to many hooks:
if (line.Contains('%') || line.Contains('#') || line.Contains("") && !line.Contains(','))
Second, as stated before, line.Contains("") will always return true. Perhapse you are missing a space or something.
Last, searching a string (or an array of characters) for the orrucance of a character is FAST! The whole search-operation is just one simple operation at assembly level (REP SCASW). In this case you have to search for more than once characters, which will result in one or more simple assembly instructions. Other statements in C# are perhapse shorter, but probably not faster.
Search for a string inside a string is slightly slower, so try to remove the Contains("").
Other operations (with LINQ or REGEX) will probably result into more: memory-operations (for arrays, delegates, result types), more analyzation (multiple characters inside an array of characters), etc. etc.
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I notice a lot of code where people do something like:
myClass.someMethod(something here, $1);
The $1 is picking up a value from "something here"?
What is this known as? I can't seem to find it anywhere? But this step, process is used in cases with regex quite a bit..
You'll often see this in regular expressions where $1 represents a capture group that you're carrying over into the new value.
For example, suppose we're building a tweet-parser for our website. We want to find # references in the tweet, and convert them into links to those particular accounts:
// Our Tweet
$t = "I am #jonathansampson, and I work with #appendTo.";
// Find every occurence of #something, capture 'something'
echo preg_replace("/#([a-z]+)/i", "<a href='http://twitter.com/$1'>$0</a>", $t);
Note here that we're matching every occurrence of #something, but we're wrapping the username portion in ( and ) so that we can handle it individually in our replacement text. The entire pattern is represented by $0, which will hold the value in its entirety from # to the last char in the username.
The same is true for JavaScript:
var tweet = "I am #jonathansampson, and I work with #appendTo.",
patrn = /#([a-z]+)/gi,
links = tweet.replace(patrn, "<a href='http://twitter.com/$1'>$&</a>");
The variable links now contains the value:
console.log(links);
/*
"I am <a href='http://twitter.com/jonathansampson'>#jonathansampson</a>, and
I work with <a href='http://twitter.com/appendTo'>#appendTo</a>."
*/
You might note that I used $& in JavaScript to grab the entire matched pattern while using $0 in PHP - we have to deal with these differences in life. My apologies ;)
If you are talking about javascript, $ can be used in declarations, so it could be a few things.
For example you could declare a variable as
var $1 = 1;
Then use it in your call
myClass.someMethod(something here, $1);
Equally it could be a reference to a function.
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
How would I convert the following code to use the ?: operator.. Is it Possible?
tbtotalamount.Text = string.Format("{0:n2}", dtl.Compute("sum(NetPay)", ""));
if (tbtotalamount.Text.Length == 0)
{
tbtotalamount.Text = "0";
}
The quoted code wouldn't benefit from using the ? : operator, which is called the conditional operator (sometimes called "the ternary operator" although technically, it's only a ternary operator — e.g., an operator that has three operands).
Typically the conditional operator is handy for when you have a variable and want to assign one of two values to it on the basis of a condition. So code in this form:
if (someCondition) {
a = "one value";
}
else {
a = "a different value";
}
can be rewritten
a = someCondition ? "one value" : "a different value";
In your case, though, you don't know that tbtotalamount.Text is blank until after you've done the string.Format, so you're better off leaving it with the if.
Yes. Here's how:
string test = string.Format("{0:n2}", dtl.Compute("sum(NetPay)", ""));
tbttotalamount.Text = test.length == 0 ? "0" : test;
Sorry to see so many downvotes, I'm not familiar with the ? (ternary) operator for a very long time either. I think it is very handy.
To the left of it is your test expression, it should be a boolean after evaluation. To the right is what the operator returns: if true, it will return the value to the left of the :. If false, the value to the right. Note that the whole expression returns something, and the compiler needs you to do something with it. You can't use the ternary operation to replace if-else statements that call functions whose return type is void.
What I mean to say is that a lot of people who've never used it before (like me) seem to think this is a pure if-else replacement, which it is not.
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
explain the rangevalidator control,is it take string also? explain thank you
It supports
Currency
Date
Double
Integer
String
For comparing strings better to use Regularexpressionvalidator instead of Rangevalidator.
In case of type string for the range validator it will only check the character by character, not the length of the string.
Yes, it does support string range validation.
Please look at the documentation before asking question.
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.rangevalidator.aspx
MSDN:
The RangeValidator control allows you to check whether a user's entry is between a specified upper and a specified lower boundary. You can check ranges within pairs of numbers, alphabetic characters, and dates. Boundaries are expressed as constants.