The object i is from database.
PrDT is a string, PrDateTime is DataTimeOffset type, nullable
vi.PrDT = i.PrDateTime.Value.ToString("s");
What is the quick way?
I don't want if else etc...
Using the conditional operator:
vi.PrDT = i.PrDateTime.HasValue ? i.PrDateTime.Value.ToString("s") :
string.Empty;
You can do an extensions method:
public static class NullableToStringExtensions
{
public static string ToString<T>(this T? value, string format, string coalesce = null)
where T : struct, IFormattable
{
if (value == null)
{
return coalesce;
}
else
{
return value.Value.ToString(format, null);
}
}
}
and then:
vi.PrDT = i.PrDateTime.ToString("s", string.Empty);
string.Format("{0:s}", i.PrDateTime)
The above will return back an empty string if it's null. Since Nullable<T>.ToString checks for a null value and returns an empty string if it is, otherwise returns a string representation (but can't use formatting specifiers). Trick is to use string.Format, which allows you to use the format specifier you want (in this case, s) and still get the Nullable<T>.ToString behavior.
return (i.PrDateTime.Value ?? string.Empty).ToString();
Just tested and it seems to work.
return i.PrDateTime.Value.ToString("s") ?? string.Empty;
Related
Is there Better way to check if a string is empty or null using Null Coalescing operator .When I use empty value to a string instead of null the null Coalescing operator failed to get me the desired result.
string x = null;
string y = x ?? "Default Value";
Console.WriteLine(y);
Here if I replace x = null with x="" this doesnt work.
If I use String.IsNullOrEmpty method
if(String.IsNullOrEmpty(x)
{
y= "default value"
}
{
y =x
}
My code block is having multiple lines and I want to make it simple. Can you suggest a better way to keep the code clean and simple. As it is used in many places.
You can use the ? operator
string x = null;
string y = string.IsNullOrEmpty(x) ? "Default Value" : x;
Console.WriteLine(y);
Given that you say "it is used in many places" then it might be appropriate to write an extension method to help with this:
public static class StringExt
{
public static string OrIfEmpty(this string? self, string defaultValue)
{
return !string.IsNullOrEmpty(self) ? self : defaultValue;
}
}
Which you would use like so:
string? x = null;
string y = x.OrIfEmpty("test");
Console.WriteLine(y); // "test"
You could probably choose a better name for OrIfEmpty() depending on taste.
However, note that this suffers from the drawback that the default value is always evaluated. If obtaining the default is expensive, then using this extension method will hurt performance because the default will always be evaluated even if it's not used.
To circumvent that issue you'd add an extension method to allow you to pass a Func<string> instead:
public static string OrIfEmpty(this string? self, Func<string> defaultValue)
{
return !string.IsNullOrEmpty(self) ? self : defaultValue();
}
Then when calling it you'd have to pass a delegate for the default, e.g:
public sealed class Program
{
public static void Main()
{
string? x = null;
string y = x.OrIfEmpty(expensiveDefault);
Console.WriteLine(y);
}
static string expensiveDefault()
{
return "test";
}
}
I'm just posting this for consideration. Myself, I would just use Marco's answer. But if you have a LOT of code that does it, then just maybe...
I am able to assign a variable like below:
if (Session["myVariable"] != null)
{
string variAble = Session["myVariable"].ToString();
}
Is there a method which checks whether an object is null or not and then assign if it is not null?
string variAble = Session["myVariable"] ?? "";
EDIT A slightly more robust form, as suggested by #hatchet, is:
string variAble = (Session["myVariable"] ?? "").ToString();
While this isn't anything new, you can use the conditional operator to potentially simplify this:
string variable = Session["myVariable"] != null ? Session["myVariable"].ToString() : "Fallback";
You could write an extension method, as those still work with null objects.
public static class StringExtensions
{
public static String ToNullString(this object o)
{
return o == null ? "" : o.ToString();
}
}
I would consider it poor form though - it'll be confusing to whoever will be supporting the code after you, or even to you a few months down the track. It's probably better to just do the null check.
Is there a single-line way of casting an object to a decimal? data type?
My code looks something like this:
foreach(DataRow row in dt.Rows)
{
var a = new ClassA()
{
PropertyA = row["ValueA"] as decimal?,
PropertyB = row["ValueB"] as decimal?,
PropertyC = row["ValueC"] as decimal?
};
// Do something
}
However casting an object to a decimal? doesn't work the way I expect it to, and returns null every time.
The data rows are read from an Excel file, so the data type of the object in each row is either a double if there is a value, or a null string if it's left blank.
The suggested method to perform this cast is to use decimal.TryParse, however I do not want to create a temp variable for every decimal property on the class (I have about 7 properties on my actual class that are decimals, not 3).
decimal tmpvalue;
decimal? result = decimal.TryParse((string)value, out tmpvalue) ?
tmpvalue : (decimal?)null;
Is there a way I can cast a potentially null value to a decimal? in a single line?
I tried the answer posted here, however it doesn't appear to be working and gives me a null value as well because row["ValueA"] as string returns null.
Your best bet is to create an extension method. This is what I use, although you can tweak it to return a decimal? instead.
public static class ObjectExtensions
{
public static decimal ToDecimal(this object number)
{
decimal value;
if (number == null) return 0;
if (decimal.TryParse(number.ToString().Replace("$", "").Replace(",", ""), out value))
return value;
else
return 0;
}
public static decimal? ToNullableDecimal(this object number)
{
decimal value;
if (number == null) return null;
if (decimal.TryParse(number.ToString().Replace("$", "").Replace(",", ""), out value))
return value;
else
return null;
}
}
You would then use it by calling .ToDecimal() on any object, the same way you would call .ToString().
It's not one line, but it is only a single function call at the point where it's used, and it's very reusable.
Edited to add nullable version
providing there is a value it reads as a double, otherwise I think it's a string
Okay, so this complicates matters as sometimes you need to parse it and sometimes you don't.
The first thing we'll want to do is check if it's already a double and cast it, because casting is much cheaper than parsing; parsing is expensive.
Given that this logic will be non-trivial, it belongs in it's own method:
public static deciaml? getDecimal(object rawValue)
{
decimal finalValue;
double? doubleValue = rawValue as double?;
if(doubleValue.HasValue)
return (decimal) doubleValue.Value;
else if(decimal.TryParse(rawValue as string, out finalValue))
{
return finalValue;
}
else
{
return null;//could also throw an exception if you wanted.
}
}
If you know that it will always be a double, and you'll never want the string values, then it's easier still. In that case you need to cast it to a double, first, since that's it's real type, and then you can easily convert it to a decimal:
PropertyA = (decimal?)(row["ValueA"] as double?);
decimal.TryParse is the way to go. Just create a helper method and return the value. Pretty much the same code you mentioned:
private decimal? convertToNullableDecimal(object value){
decimal tmpvalue;
return decimal.TryParse((string)value, out tmpvalue) ? tmpvalue : (decimal?)null;
}
UPDATE
This assumes you need a nullable decimal back. Otherwise do as suggested in other answers, use the built-in method: Convert.ToDecimal
Try something like
Func<object, decimal?> l_convert =
(o) => decimal.TryParse((o ?? "").ToString(), out tmpvalue) ? tmpvalue : (decimal?)null;
var a = new ClassA()
{
PropertyA = l_convert(row["ValueA"]),
PropertyB = l_convert(row["ValueB"]),
PropertyC = l_convert(row["ValueC"])
};
Hope this helps
decimal temp;
foreach(DataRow row in dt.Rows)
{
var a = new ClassA()
{
PropertyA = Decimal.TryParse(row["ValueA"].ToString(), out temp) ? Convert.ToDecimal(row["ValueA"].ToString()) : (Decimal?) null,
....
};
// Do something
}
You may try the Decimal.Parse method.
public static decimal ToDecimal(this string value){
try
{
return Decimal.Parse(value);
}
catch (Exception)
{
// catch FormatException, NullException
return 0;
}
}
// use
PropertyA = row["ValueA"].ToString().ToDecimal();
PropertyB = row["ValueB"].ToString().ToDecimal();
PropertyC = row["ValueC"].ToString().ToDecimal();
Convert.ToDecimal(object) almost does what you want. It will convert the double value properly (without going to a string first), and also handle other types that can convert to decimal. The one thing it doesn't do well is the null conversion (or converting of String.Empty to null). This I would try to handle with an extension method.
public static class ObjectToDecimal
{
public static decimal? ToNullableDecimal(this object obj)
{
if(obj == null) return null;
if(obj is string && String.Empty.Equals(obj)) return null;
return Convert.ToDecimal(obj);
}
}
Just remember that Convert.ToDecimal(object) can thrown exceptions, so you'll have to watch out for that.
Basically I want the following generic function:
public string StringOrNull<T> (T value)
{
if (value != null)
{
return value.ToString();
}
return null;
}
I know I could use a constraint such as where T: class, but T can be a primitive type, Nullable<>, or a class. Is there a generic way to do this?
Edit
Turns out I jumped the gun. This actually works just fine as this sample shows:
class Program
{
static void Main(string[] args)
{
int i = 7;
Nullable<int> n_i = 7;
Nullable<int> n_i_asNull = null;
String foo = "foo";
String bar = null;
Console.WriteLine(StringOrNull(i));
Console.WriteLine(StringOrNull(n_i));
Console.WriteLine(StringOrNull(n_i_asNull));
Console.WriteLine(StringOrNull(foo));
Console.WriteLine(StringOrNull(bar));
}
static private string StringOrNull<T>(T value)
{
if (value != null)
{
return value.ToString();
}
return null;
}
}
default Keyword in Generic Code
In generic classes and methods, one issue that arises is how to assign a default value to a parameterized type T when you do not know the following in advance:
Whether T will be a reference type or a value type.
If T is a value type, whether it will be a numeric value or a struct.
Here's a fun one:
public static class ExtensionFunctions{
public static string ToStringOrNull( this object target ) {
return target != null ? target.ToString() : null;
}
}
The cool part? This will work:
( (string) null ).ToStringOrNull();
So will this:
5.ToStringOrNull();
Extension functions are pretty awesome... they even work on null objects!
If you pass a primitive type, it will automatically be boxed, so you don't need to worry about the null comparison. Since boxing occurs automatically, you can even explicitly compare an int to null without an error, but the result will always be false (and you'll probably get a compiler warning telling you so).
You can use default keyword to return the default of T:
public string StringOrNull<T> (T value)
{
.....
return default(T).ToString();
}
Why generic?
public string StringOrNull (object value)
{
if (value != null){
return value.ToString();
}
return null;
}
I have a DateTime? variable, sometimes the value is null, how can I return an empty string "" when the value is null or the DateTime value when not null?
Though many of these answers are correct, all of them are needlessly complex. The result of calling ToString on a nullable DateTime is already an empty string if the value is logically null. Just call ToString on your value; it will do exactly what you want.
string date = myVariable.HasValue ? myVariable.Value.ToString() : string.Empty;
Actually, this is the default behaviour for Nullable types, that without a value they return nothing:
public class Test {
public static void Main() {
System.DateTime? dt = null;
System.Console.WriteLine("<{0}>", dt.ToString());
dt = System.DateTime.Now;
System.Console.WriteLine("<{0}>", dt.ToString());
}
}
this yields
<>
<2009-09-18 19:16:09>
Calling .ToString() on a Nullable<T> that is null will return an empty string.
You could write an extension method
public static string ToStringSafe(this DateTime? t) {
return t.HasValue ? t.Value.ToString() : String.Empty;
}
...
var str = myVariable.ToStringSafe();
All you need to do is to just simply call .ToString(). It handles Nullable<T> object for null value.
Here is the source of .NET Framework for Nullable<T>.ToString():
public override string ToString() {
return hasValue ? value.ToString() : "";
}
DateTime? d;
// stuff manipulating d;
return d != null ? d.Value.ToString() : String.Empty;
DateTime d?;
string s = d.HasValue ? d.ToString() : string.Empty;
DateTime? MyNullableDT;
....
if (MyNullableDT.HasValue)
{
return MyNullableDT.Value.ToString();
}
return "";
if (aDate.HasValue)
return aDate;
else
return string.Empty;
According to Microsoft's documentation:
The text representation of the value of the current Nullable object if the HasValue property is true, or an empty string ("") if the HasValue property is false.