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.
Related
As documented in the Boolean.ToString(IFormatProvider) method doc, the IFormatProvider provider does not impact the constant "True/False" output.
Now, is there a way to however translate the "True" to "Verdadero"?
public static void Main(string[] args)
{
//Your code goes here
Console.WriteLine("Hello, world!");
System.Globalization.CultureInfo ci = new CultureInfo("es-ES");
Console.WriteLine(true.ToString(ci));
}
// Hello, world!
// True
There isn't a library-based solution to your question, nor should there be. The reason is that a string representation of System.Boolean is unlikely to be useful for anything but the most trivial of localization. Note that is not the case for floating-point numbers where a culture-specific . or , can be applied when formatting. Dates (System.DateTime) have some localization support from the operating system itself, so .NET is able to build on that; this is not the case for System.Boolean.
Usually, there will be other words in addition to just "True" (or "False"); those words will have to be translated too. And, depending on the language and those other words, you might not be able to do simple string concatenation: string message = baseMessage + b.ToString();
Instead, you should store your strings in resource files and retrieve the right one.
bool b = ...;
string message = b ? Properties.Resources.TrueMessage : Properties.Resources.FalseMessage;
See How to use localization in C# for more details.
As per the docs, Boolean.ToString(IFormatProvider) will not reflect culture specific strings.
However, one workaround could be to create an extension method on the Boolean object:
public static class BoolExtensions
{
public static string ToSpanishString(this bool val)
{
return val ? "Verdadero" : "Falso";
}
}
You can achieve this in the following way:
bool test = true;
Console.WriteLine(test ? "Verdadero" : "Equivocado");
The first value is always the truthy one, the second is the falsy.
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.
I've made a method to convert a datetime object to a date-only format. In order to access it, I have to assign the value of my parameter to the value that will be in a datatable. The obvious method would thus be to add a ? after the DateTime object to make it nullable, however this removes it's methods (or at least, the one I need to use), making my method worthless.
string dateWithOutTime(DateTime? datetime)
{
string reply = datetime.Date.ToString();
return reply;
}
usage:
string str = dateWithOutTime(*DataSet*.*DataTable[n]*.Rows[n][n] as DateTime?);
Is there a way to accomplish this without adding any extra objects?
Note: a star (*) denotes a variable type/object
DateTime? doesn't have the same methods as DateTime, they're different types. You have to retrieve the actual datetime value using DateTime?'s Value property:
string dateWithOutTime(DateTime? datetime)
{
if(datetime.HasValue)
return datetime.Value.Date.ToString();
else
return //...
}
Read the documentation for Nullable<T> here.
Unless I misunderstand your problem, I'd say you need to check if your DateTime? parameter is null or not. If it is, return an empty string (or a string you want to display for missing dates). If it isn't, you can use the Value property:
string dateWithOutTime(DateTime? datetime)
{
return datetime.HasValue ? datetime.Value.Date.ToString() : String.Empty;
}
Update
If you only want the date-part in your string and you want it to be culture-sensitive, you can use ToShortDateString() instead of ToString(). You can even leave out the Date property:
string dateWithOutTime(DateTime? datetime)
{
return datetime.HasValue
? datetime.Value.ToShortDateString()
: String.Empty;
}
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.
I have a service that validates the user input. So, in other layers I am just using the below statement to get the amount value assuming that it is already validated.
But while writing unit test cases, I realized this is failing. So, my question is do we need to ALWAYS try to parse the values whenever string values needs to be converted to actual types.
var amountValue = Convert.ToDecimal(string.Format("{0}.{1}", view.amount, view.fraction))
You should parse strings because that's what you actually want to do.
A type conversion is something different than parsing.
Imagine a case where in the US you separate decimals with a dot . and in EU you'd use a comma ,. You can't really know how the locale separates decimals and whatnot (especially dates are crucial and should be PARSED no CONVERTED).
That said, the rule user input => parse is quite straight forward.
Here is a convert method based on generics:
public static void Convert<T>(string text, out T value, CultureInfo culture) where T : IConvertible
{
if (typeof(T).IsEnum)
{
value = (T) Enum.Parse(typeof (T), text, true);
}
else
{
value = (T)System.Convert.ChangeType(text, typeof(T), culture);
}
}