Is better to use the below statement
Convert.ToInt32("0" + stringValue)
If not then why?
I know that it is better to user int.TryParse() function, which is better, but what about the above statement.
Better than what?
Personally, I think that using Convert.ToInt32("0" + stringValue) is an anti-pattern.
It doesn't provide anything useful, since:
A positive integer will still result in the same value.
If you pass it a negative number, it will throw.
It doesn't add any extra error checking
It DOES create an extra string concatenation, which is not used for anything, reducing performance for no reason
It adds extra complexity for no reason.
Just use Convert.ToInt32(stringValue) directly, or int.TryParse if you don't want to have exception handling in place.
The only case when that would have any use is if the string variable is a null reference. Concatenating with a zero character is totally pointless, though. As we are only after the null check performed by the string concatenation, a better version would concatenate with an empty string instead, as that doesn't break for negative values:
Convert.ToInt32(String.Empty + stringValue)
A better solution as it doesn't do a string concatenation:
Convert.ToInt32(stringValue ?? String.Empty)
An even better solution would be to check for the null value first, so that you don't have to parse the known string:
stringValue == null ? 0 : Convert.ToInt32(stringValue)
Related
if((string)row["ProductID"].ToString() == txtBarcode.Text)
I want to search a row if the value of the txtbox is the same as my datatable but i have an error.. it says that Possible unintended reference comparison; to get a value comparison, cast the left hand side to string. i just use .ToString() and Convert.ToString() but still have that error.
Your .ToString() is converting the row value to a string, so you don't also need to cast it on the left with (string)
Ie. if(row["ProductID"].ToString() == txtBarcode.Text)
Personally, I'd stare clear of using == operator with anything but ints, chars and whether this instance is that instance.
A better way of comparing strings is to use string.Equals(string) string.contains(string) or string.indexOf(string)
Note : if you are comparing with TextBox value then it is better to trim the values before comparing to remove the whitespaces using Trim() method.
Solution 1: if you want to find the excat match then you need to use Equals() method.
if(row["ProductID"].ToString().Equals(txtBarcode.Text.Trim())
{
/* do something*/
}
Solution 2: if you want to find the part of the string then you can use String.Contains() method as below:
if(row["ProductID"].ToString().Contains(txtBarcode.Text.Trim())
{
/* do something*/
}
You need to do one of the above. Either do a cast (string)row["ProductId"] or Convert.ToString(row["ProductId"]) for converting the value to string. But casting using (string)row["ProductId"] is likely to throw InvalidCastException. So may be ToString() would be better.
9 times out of 10, when I want to use the Substring() method on a string, it's because I want to shave some characters off the END of the string, not the start. While the default Substring does have support for this, it does so by taking a second parameter which is the length of the desired string, rather than the endpoint. This means if I consistently want to shave off N characters off of a series of strings of differing length, I have to do an extra step, which can result in a good deal more code. Take for example:
//Shaving the first N chars
string trimmed = foo.bar.widget.GetType().Name.Substring(N);
vs.
//Shaving the last N chars
string trimmed = foo.bar.widget.GetType().Name.Substring(0, foo.bar.widget.GetType().Name.Length - N);
or maybe to save the extra function call, use a second line:
string name = foo.bar.widget.GetType().Name;
string trimmed = name.Substring(0, name.Length - N);
Either way, you're basically doubling the amount of code necessary to shave characters off the end of the string rather than the beginning. My modification would be simple. If you pass a negative N (which would otherwise be meaningless), it would shave -N characters off the end of the string instead of the beginning. I can already code this up with an extension method:
public static string MySubstring(this string str, int val)
{
return (val > 0) ? str.Substring(val) : str.Substring(0, str.Length + val);
}
And then when I want to shave off the final N chars, I just do:
string trimmed = foo.bar.widget.GetType().Name.MySubstring(-N);
Short and sweet, just like shaving off the beginning characters. My question is - would it be possible to override the behavior of the default Substring() function so that I can do this without having to use my own unique name for the function? It's not like it would invalidate any existing code, because previously there was no reason to pass it a negative number, and doing so would simply throw an exception and crash. This is just one of those simple no-nonsense features that feels like it should've been part of the implementation to begin with.
According to C# documentation, you can use extension methods to extend a class or interface, but not to override them. An extension method with the same name and signature as an interface or class method will never be called. So the answer is "No".
Arguably, this is a good thing™, because otherwise your code would become a nightmare to read to someone not familiar with your extension.
Note: str.Substring(0, str.Length + val); can be replaced with str.Remove(str.Length + val)
You can't override a method on string in the strict sense using extension methods, as the compiler will always choose an instance method over an extension method with the same signature when compiling a method call. However, you can achieve something close to what you want using named arguments. This should also help avoid readability issues. Here's an example
public static string Substring(this string #this, int trimFromEnd)
{
return #this.Substring(0, #this.Length - trimFromEnd);
}
// if you do
"abc".Substring(1) -> returns "bc"
// if you do
"abc".Substring(trimFromEnd: 1) -> returns "ab"
Personally, I find this a bit more readable than Substring(-1) or just Substring(varName), where varName happens to be negative.
I am doing localization for ASP.NET Web Application, when user enters a localized string "XXXX" and i am comparing that string with a value in my localized resource file.
Example :
if ( txtCalender.Text == Resources.START_NOW)
{
//do something
}
But When i do that even when the two strings(localized strings) are equal, it returns false. ie.
txtCalender.Text ="இப்போது தொடங்க"
Resources.START_NOW="இப்போது தொடங்க"
This is localized for Tamil.
Please help..
Use one of the string.Equals overloads that takes a StringComparison value - this allows you to use the current culture for comparison..
if ( txtCalender.Text.Equals(Resources.START_NOW, StringComparison.CurrentCulture))
{
//do something
}
Or, if you want case insensitive comparison:
if ( txtCalender.Text.Equals(Resources.START_NOW,
StringComparison.CurrentCultureIgnoreCase))
{
//do something
}
I found the answer and it works. Here is the solution,
it was not working when i tried from Chrome browser and it works with Firefox. Actually when i converted both string to char array,
txtCalender.Text Returns 40 characters and Resource.START_NOW returned 46. So i have tried to Normalize the string using Normalize() method
if(txtCalender.Text.Normalize() == Resources.START_NOW.Normalize())
It was interpreting one character as two different characters when i didn't put normalize method.
it has worked fine. Thanks for your answers.
You can compare with InvariantCulture in String.Equals (statis method):
String.Equals("XXX", "XXX", StringComparison.InvariantCulture);
Not sure whether this helps though, could others comment on it? I've never come across your actual error.
Use String.Equals or String.Compare.
There is some performance differences between these two. String.Compare is faster than String.Equal because String.Compare is static method and String.Equals is instance method.
String.Equal returns a boolean. String.Compare returns 0 when the strings equal, but if they're different they return a positive or negative number depending on whether the first string is before (less) or after (greater) the second string. Therefore, use String.Equals when you need to know if they are the same or String.Compare when you need to make a decision based on more than equality.
You probably need to use .Equals
if(txt.Calendar.Text.Equals(Resources.START_NOW))
{ //...
And if case-insensitive comparison is what you're after (often is) use StringComparison.OrdinalIgnoreCase as the second argument to the .Equals call.
If this isn't working - then can I suggest you breakpoint the line and check the actual value of Resources.START_NOW - the only possible reason why this equality comparison would fail is if the two strings really aren't the same. So my guess is that your culture management isn't working properly.
Following code will cause exception:
string IDs = "";
IDs = IDs.Replace("", "");
Why?
It's right in the documentation for string.Replace(). If you try to replace with the "oldValue" parameter as an empty string, it throws an exception.
Exception Condition
ArgumentException oldValue is the empty string ("").
If you think about it, what are you actually trying to do when you try to find an empty string in another string and replace it with something? Conceptually it doesn't make sense.
String cannot be of zero length.
Probably explains why.
It throws an exception because "" would never be found.
It can be argued that both "" does not exist within a string, or that there are an infinite number of "" within any string.
It just plain don't make sense to replace an empty string with an empty string.
I'd guess it's because string.Replace() loops through characters from 0 to its .Length. Obviously this would just skip the loop as there would be nothing to loop through, perhaps they threw a throw in there out of paranoia?
Well, what do you expect?
You want to replace nothing with nothing? What exactly do you want to do?
Let's say the old string was "ABC", what would you want it to be after your call to Replace?
In this particular case, the exception thrown is an ArgumentException, and the text of it is that "String cannot be of zero length".
So, the criteria of calling the .Replace method is that what you want to replace is not a string without contents.
Let's check the documentation of String.Replace(String, String):
Under Exceptions it says:
ArgumentNullException, if oldValue is a null reference (Nothing in Visual Basic).
or
ArgumentException, if oldValue is the empty string ("").
So everything is behaving like expected.
The reason for this is that conceptually, every string contains an infinite number of empty strings at the start, at the end, and between characters. (This is why foo.IndexOf("") will always return 0 for any string foo.) Replacing all the infinite amount of empty strings with something else makes no sense as an operation.
I have a DataRow and I am getting one of the elements which is a Amount with a dollar sign. I am calling a toString on it. Is there another method I can call on it to remove the dollar sign if present.
So something like:
dr.ToString.Substring(1, dr.ToString.Length);
But more conditionally in case the dollar sign ever made an appearance again.
I am trying to do this with explicitly defining another string.
Convert.ToString(dr(columnName)).Replace("$", String.Empty)
--
If you are working with a data table, then you have to unbox the value (by default its Object) to a string, so you are already creating a string, and then another with the replacement. There is really no other way to get around it, but you will only see performance differences when dealing with tens of thousands of operations.
You could also use
string trimmed = (dr as string).Trim('$');
or
string trimmed = (dr as string).TrimStart('$');
If you are using C# 3.0 or greater you could use extension methods.
public static string RemoveNonNumeric(this string s)
{
return s.Replace("$", "");
}
Then your code could be changed to:
((String)dr[columnName]).RemoveNonNumeric();
This would allow you to change the implementation of RemoveNonNumeric later to remove things like commas or $ signs in foreign currency's, etc.
Also, if the object coming out of the database is indeed a string you should not call ToString() since the object is already a string. You can instead cast it.
Regex would work.
Regex.Replace(theString, "$", "");
But there are multiple ways to solve this problem.
dr[columeName].ToString().Replace("$", String.Empty)
Why don't you update the database query so that it doesn't return the dollar sign? This way you don't have to futz with it in your C# code.