while am trying to convert the return value of add method to string it is not returning any value in console.while i remove the tostring method it is returning value.if i write any character inside the double quote it is showing in console.
what is happening while am calling tostring method?
if i didn't put any double quote as parameter it is showing compile time error like (specify culture of string)
what is the purpose of specifying culture while converting int to string?
i think i can convert integer value to string by calling tostring method,why can't i do conversion in this scenario?
private static int Add(int x,int y)
{
return x+y;
}
static void Main(string[] args)
{
Console.WriteLine(Add(23,54).ToString(""));
Console.ReadKey();
}
thanks.
It's all about implementation;
From Int32.ToString(string)
If format is null or an empty string (""), the return value of this
instance is formatted with the general numeric format specifier ("G").
That's why .ToString("") is equal to .ToString() because
From Int32.ToString()
The ToString() method formats an Int32 value in the default ("G", or
general) format by using the NumberFormatInfo object of the current
culture.
I tried all cultures to format with .ToString("") and no culture returns null or empty string.
foreach (var c in CultureInfo.GetCultures(CultureTypes.AllCultures))
{
if((77).ToString("G", c) != "77")
Console.WriteLine (c.Name);
}
Blue line probably there is a plugin (maybe ReSharper) that warn you to use another overloads that takes CultureInfo as a parameter for example.
Use ToString with no parameters
Add(23,54).ToString()
Using the parameter you specified you set a culture for the string conversion.
More here.
simply specify your culture of string as string.empty
Console.WriteLine(Add(23,54).ToString(string.Empty));
Console.ReadKey();
Culture Name:"" (empty string)
Culture Identifier:0x007F
Language-Country/Region:invariant culture
http://msdn.microsoft.com/en-us/library/system.globalization.cultureinfo%28v=vs.71%29.aspx
string.Empty is a read-only field whereas "" is a compile time constant.some Places they behave differently.
Related
I have a CSV Reader, so I have a generic casting method. It it, I do this:
try
{
TypeConverter converter = TypeDescriptor.GetConverter(type);
if (converter != null)
{
result = converter.ConvertFromString(null, culture, value);
return true;
}
result = type.GetDefault();
return true;
}
catch
{
result = type.GetDefault();
return false;
}
However if I pass:
type: int
value: "123.024"
culture: de-DE
The converter always fails and returns 0, instead of correctly treating . as a thousands separator.
Anyone know how to get it to work?
Because the Int32Converter calls Int32.Parse internally, and Int32.Parse does not support thousands separators in the string passed to it.
More specifically, Int32.Parse format described below:
The s parameter contains a number of the form:
[ws][sign]digits[ws]
Items in square brackets ([ and ]) are optional. The following table
describes each element. Element Description
ws Optional white space.
sign An optional sign
digits A sequence of digits ranging from 0 to
9.
The s parameter is interpreted using the NumberStyles.Integer style. In addition to decimal digits, only leading and trailing spaces
together with a leading sign are allowed. To explicitly define the
style elements that can be present in s, use either the
Int32.Parse(String, NumberStyles) or the
Int32.Parse(String, NumberStyles, IFormatProvider) method.
The s parameter is parsed using the formatting information in a NumberFormatInfo object initialized for the current system culture.
For more information, see CurrentInfo. To parse a string using the
formatting information of some other culture, use the
Int32.Parse(String, NumberStyles, IFormatProvider) method.
If you were calling Int32.Parse directly, you could just call the overload that accepts a NumberStyles enum and create a composite value with the flags you want. E.g:
Int32.Parse(value, NumberStyles.Integer | NumberStyles.AllowThousands);
However, neither GetConverter() nor Int32Converter have any means of overriding the default NumberStyles of Int32.Parse, so you will either need a special case for ints or you will have to ensure that the strings passed to this function do not contain thousands separators.
I'm having an ussue with the TypeDescriptor class.
I have a cookie which contains a date - the date is converted to a string and then back again using some helper methods.
One of my staple extension methods is used to do the conversion, however it throws a forced error because the date is not convertible back from a string.
Here's the message I output:
22/01/2015 14:29:15 could not be converted to DateTime
Looks like a DateTime to me!
The problem can be overcome by using Convert.ToDateTime(), so the code in general is ok. i also use it for dates elwhere with no problems to date.
The only difference is that I'm converting in the middle of a linq statement like this:
Set = new SortedSet<TrackedItem>(set
.Split(';')
.Select(s =>
{
var parts = s.Split(',');
return new TrackedItem(
parts[0].ConvertTo<int>(),
Convert.ToDateTime(parts[1]));
}));
Any ideas?
public static T ConvertTo<T>(this object obj, bool throwInvalid = false)
where T : IConvertible
{
// Object does not require converting.
if (obj is T) return (T)obj;
// Determine if object can be converted.
var type = typeof(T);
var converter = TypeDescriptor.GetConverter(type);
var isConvertible = converter != null && converter.IsValid(obj);
var error = string.Format("'{0}' could not be converted to type {1}", obj, type.Name);
// If no conversion is available, and defaults not allowed throw an error.
(!isConvertible && throwInvalid).ThrowTrue(error);
// If the object is convertible, convert it, else return the default(T).
return isConvertible ? (T)converter.ConvertFrom(obj) : default(T);
}
I'm guessing from your date example that you're running in the en-GB culture. Unfortunately, to draw liberally from this related q/a, IsValid always uses CultureInfo.InvariantCulture (US date format) to decide its answer. So when running in en-GB with a date such as your example, IsValid will return false; but ConvertFrom, which by default uses the current thread culture will succeed!
Interestingly, the latest docs for IsValid massively hedge the question of whether this is actually a bug:
The IsValid method is used to validate a value within the type
rather than to determine if value can be converted to the given type.
For example, IsValid can be used to determine if a given value is
valid for an enumeration type.
So really you shouldn't be using IsValid here at all - you should be doing what the same docs go on to suggest:
You can write your own WillConvertSucceed method by wrapping the
ConvertTo and ConvertFrom methods in exception blocks.
And in that method you can be sure to use the CultureInfo you actually care about.
Hi i m using given below method to convert in to string its working fine chrome but in IE its through exception Input string was not in a correct format. at this line
s = TimeSpan.FromSeconds(Convert.ToDouble(time));
these are values i m passing to it
600, 298.8, 65505, 69, 70, 20.5, 20.5, 20.5, 20.5, 1840.4, 682, 1040.3
in chrome its working but in IE it gives exception on second value when i change the culture to french language please help me out what is the problem
public static String ConvertTimeToString(this string time)
{
if (String.IsNullOrEmpty(time))
{
return time;
}
TimeSpan s;
if (time.IndexOf(':') >= 0)
{
s = TimeSpan.Parse(time);
}
else
{
s = TimeSpan.FromSeconds(Convert.ToDouble(time));
}
return s.ConvertTimeToString();
}
The failure is probably in the call Convert.ToDouble. Your code probably executes in a CultureInfo that has ',' as decimal separator, but your values use '.'. I would advice you to use Double.TryParse using a CultureInfo that has '.' as decimal separator instead:
Double value;
if (Double.TryParse(time, NumberStyles.Any, CultureInfo.GetCultureInfo("en-US"), out value))
{
s = TimeSpan.FromSeconds(value);
}
You need to specify an IFormatProvider when you use Convert.ToDouble(time):
Convert.ToDouble(time, CultureInfo.InvariantCulture)
Specifying CulturInfo.InvariantCulture specifies a culture that expect floating points written as 1.234 (note the period). The source of your problem may be that you time is in the format 1,234 (note the comma). Or maybe it is the reverse: You don't specify an IFormatProvider and the current culture of you ASP.NET process uses comma as a decimal separator, but the string provided uses period?
If the decimal point used isn't consistent you should either fix it at the source (not sure what the source is here) or as a last resort you can replace comma by period:
Convert.ToDouble(time.Replace(",", ".") , CultureInfo.InvariantCulture)
However, trying to parse a string and not knowing the what to expect is not the best thing to do.
can i override Convert.ToDateTime()? I don't want 100 times or more check if string is nul and if is not then convert it to DateTime. Can i override this function to check if is null then will return null otherway convert it.
No, you can't override static methods. But you can write your own static method:
// TODO: Think of a better class name - this one sucks :)
public static class MoreConvert
{
public static DateTime? ToDateTimeOrNull(string text)
{
return text == null ? (DateTime?) null : Convert.ToDateTime(text);
}
}
Note that the return type has to be DateTime? because DateTime itself is a non-nullable value type.
You might also want to consider using DateTime.ParseExact instead of Convert.ToDateTime - I've never been terribly fond of its lenient, current-culture-specific behaviour. It depends where the data is coming from though. Do you know the format? Is it going to be in the user's culture, or the invariant culture? (Basically, is it user-entered text, or some machine-generated format?)
ToDateTime can't be overriden but you can use TryParse:
bool valid = DateTime.TryParse("date string", out d);
You can use DateTime.Parse instead, if you are sure that your string is in correct format.
private void ReadUnitPrice()
{
Console.Write("Enter the unit gross price: ");
unitPrice = double.Parse(Console.ReadLine());
}
This should work, but I'm missing something obvious. Whenever I input a double it gives me the error: System.FormatException: Input string was not in a correct format.
Note that 'unitPrice' is declared as a double.
It could be that you're using wrong comma separation symbol or even made an other error whilst specifying double value.
Anyway in such cases you must use Double.TryParse() method which is safe in terms of exception and allows specify format provider, basically culture to be used.
public static bool TryParse(
string s,
NumberStyles style,
IFormatProvider provider,
out double result
)
The TryParse method is like the Parse(String, NumberStyles,
IFormatProvider) method, except this method does not throw an
exception if the conversion fails. If the conversion succeeds, the
return value is true and the result parameter is set to the outcome of
the conversion. If the conversion fails, the return value is false and
the result parameter is set to zero.
EDIT: Answer to comment
if(!double.TryParse(Console.ReadLine(), out unitPrice))
{
// parse error
}else
{
// all is ok, unitPrice contains valid double value
}
Also you can try:
double.TryParse(Console.ReadLine(),
NumberStyle.Float,
CultureInfo.CurrentCulture,
out unitPrice))