I'm missing something, how do I make this work?
var now = DateTime.Now;
string loadStartDate = Request.QueryString["sd"] == String.Empty ? now.AddMonths( -14 ).ToShortDateString();
string loadEndDate = Request.QueryString[ "ed" ] == String.Empty ? now.ToShortDateString();
Basically when the page loades if sd and/or ed is blank, then fill the date with my pre-defined stuff.
You are forgetting a : and the part after it.
The conditional operator has three parts:
predicate (Request.QueryString["sd"] == String.Empty)
true branch
false branch
You are missing the false branch syntax and value.
I would write it as:
string loadStartDate = string.IsNullOrWhitespace(Request.QueryString["sd"])
? now.AddMonths( -14 ).ToShortDateString()
: Request.QueryString["sd"];
Note:
string.IsNullOrWhitespace is new to .NET 4.0, so use string.IsNullOrEmpty for prior versions.
It should be like:
string loadStartDate = Request.QueryString["sd"] == String.Empty ? now.AddMonths
( -14 ).ToShortDateString():SOME OTHER VALUE;
The syntax for the conditional operator is:
condition ? truevalue : falsevalue
You are missing the colon and the value for when the conditon is false.
You can use the conditional operator for this, but then it gets a little repetetive. Just do like this:
DateTime now = DateTime.Now;
string loadStartDate = Request.QueryString["sd"];
if (String.IsNullOrEmpty(loadStartDate)) loadStartDate = now.AddMonths(-14).ToShortDateString();
string loadEndDate = Request.QueryString[ "ed" ];
if (String.IsNullOrEmpty(loadEndDate)) loadEndDate = now.ToShortDateString();
Related
I have this weird error.
On this code, as you can, I have a query on database, return it as DataTable and explicitly declared it null. Now I have a condition to check this if this is null and pass it to a string variable. Everything works fine. I receive an empty string. No exception found.
DataTable dtDateUploaded = _BL.GetRecordByDataTableResults();
dtDateUploaded = null;
string strUploadedDate = dtDateUploaded == null ? string.Empty :
dtDateUploaded.Rows[0].IsNull(0) ? string.Empty :
dtDateUploaded.Rows[0][0].ToString();
But when I used the same condition and pass it directly to a Label control for example (and not use a string variable), I get an object reference error. I wonder why do I get an object reference error if I just used the same code on my string variable above?
LblRecordCount.Text = "Record Uploaded last: " + dtDateUploaded == null ? string.Empty :
dtDateUploaded.Rows[0].IsNull(0) ? string.Empty :
dtDateUploaded.Rows[0][0].ToString();
And the weird part is that this works:
LblRecordCount.Text = "Record Uploaded last: " + strUploadedDate;
You get this error because, in the second example, the + operator has precedence over the == operator so you are trying to concatenate the "Record Uploaded last" string to a null variable.
Instead, in the first example, the = operator has lower precedence than the == operator and no error occurs because the ternary operators are evaluated before the assignment.
You should use brackets to group the ternary operators logic together
LblRecordCount.Text = "Record Uploaded last: " + (dtDateUploaded == null ? string.Empty :
dtDateUploaded.Rows[0].IsNull(0) ? string.Empty :
dtDateUploaded.Rows[0][0].ToString());
See MSDN on C# Operators
Is it possible to rewrite this into a single line of code?
if (txtInvoiceDate.Text != "")
{
query.Parameters.AddWithValue("#InvoiceDate", SqlDbType.SmallDateTime).Value = DateTime.Parse(txtInvoiceDate.Text.ToString());
}
else
{
query.Parameters.AddWithValue("#InvoiceDate", SqlDbType.SmallDateTime).Value = DBNull.Value;
}
Yes
I have been reading about the ?: operator. I wasn't sure how this
would work in this situation. I have never used it in this case
So, according to your code you can change it to
query.Parameters.AddWithValue("#InvoiceDate", SqlDbType.SmallDateTime).Value = txtInvoiceDate.Text != "" ? DateTime.Parse(txtInvoiceDate.Text.ToString()) : DBNull.Value;
but it will be better to use string.IsNullOrWhiteSpace()
query.Parameters.Add("#InvoiceDate", SqlDbType.SmallDateTime).Value = !string.IsNullOrWhiteSpace(txtInvoiceDate.Text) ? DateTime.Parse(txtInvoiceDate.Text.ToString()) : DBNull.Value;
Read more about ?: Operator
Short answer: yes
Long answer:
query.Parameters.AddWithValue("#InvoiceDate", SqlDbType.SmallDateTime).Value = string.IsNullOrWhiteSpace(txtInvoiceDate.Text) ? DBNull.Value : DateTime.Parse(txtInvoiceDate.Text.ToString());
Background
In PHP there is a shorthand for the ternary operator:
$value = "";
echo $value ?: "value was empty"; // same as $value == "" ? "value was empty" : $value;
In JS there's also an equivalent:
var value = "";
var ret = value || "value was empty"; // same as var ret = value == "" ? "value was empty" : value;
But in C#, there's (as far as i know) only the "full" version works:
string Value = "";
string Result = Value == string.Empty ? "value was empty" : Value;
So my question is: Is there a shorthand for the ternary operator in C#, and if not, is there a workaround?
Research
I found the following questions, but they're referring to use the ternary operator as shorthand to if-else:
shorthand If Statements: C#
Benefits of using the conditional ?: (ternary) operator
And this one, but it's concerning Java:
Is there a PHP like short version of the ternary operator in Java?
What I have tried
Use the shorthand style of PHP (Failed due to syntax error)
string Value = "";
string Result = Value ?: "value was empty";
Use the shorthand style of JS (Failed because "The || operator is not applicable to string and string.")
string Value = "";
string Result = Value || "value was empty";
There is no shorthand for when the string is empty. There is a shorthand for when the string is null :
string Value = null;
string Result = Value ?? "value was null";
The coalesce ?? operator works only on null, but you could "customize" the behavior with an extension method:
public static class StringExtensions
{
public static string Coalesce(this string value, string #default)
{
return string.IsNullOrEmpty(value)
? value
: #default;
}
}
and you use it like this:
var s = stringValue.Coalesce("value was empty or null");
But I don't think it is much better than the ternary.
Note: the # allows you to use reserved words as variable names.
In my table of MySQL Db I have the field Check.
The value memorized on the field Check it could be : null or -1.
When the value memorized on the field Check is null or -1 I need in return the xxx value. and I have tried :
string Check = sdr["Check"] == DBNull.Value || sdr["Check"] == "-1,00" ? "xxx" : sdr["Check"].ToString();
Without success because the output is always -1,00.
How to do resolve this?
Please help me, thank you so much in advance.
The problem is that you are comparing the wrong objects. The values returned from System.Data result sets are wrappers around the actual value. What you want are the typed versions. Basically, the check should look like this:
int checkIndex = sdr.GetOrdinal("Check");
string Check = sdr.IsDBNull(checkIndex) || (sdr.GetString(checkIndex) == "-1,00") ? "xxx" : sdr.GetString(checkIndex);
If you "Check" is actually a number, you may want to use the IntValue("Check") call, just to deal with globalization issues if your app is ever deployed where they use a "." instead of a "," for your decimal point.
See https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldatareader(v=vs.110).aspx for the full API.
If your MySQL database is not set to use the same locale formatting as your C# application, your assumptions about number formats could be incorrect. To make a more robust version of your check, I would recommend something like this:
int checkIndex = sdr.GetOrdinal("Check");
string Check = "xxx";
double checkValue = sdr.IsDBNull(checkIndex) ? -1 : Convert.ToDouble(sdr[checkIndex]);
if (checkValue != -1)
{
Check = checkValue.ToString(CultureInfo.CurrentCulture);
}
If the data type is decimal 10,2 you need Convert.ToDecimal the value :
string Check = (sdr["Check"] == DBNull.Value || Convert.ToDecimal(sdr["Check"]) == -1) ? "xxx" : sdr["Check"].ToString();
You can compare a string empty or null by below code
string str = Your string
if(String.IsNullOrEmpty(str))
{
if yes, it comes here
}
else
{
if not, it comes here
}
The String.IsNullOrEmpty() is a bool type.
The following conversion doesn't work.
Error:"Only assignment, call, increment, decrement & new object can be
used as a statement"
VB.net
objUser.Email = IIf(IsDBNull(drow("Email")), "", drow("Email"))
C#
objUser.Email == (Information.IsDBNull(drow("Email")) ? "" : drow("Email"));
I need it in C#. Any ideas??
In C# = is asignment operator and == is comparison operator
Remove == and replace with =.
Assuming that drow is DataRow
objUser.Email = (drow.IsNull("Email") ? String.Empty : drow["Email"].ToString());
?: is ternary operator which always returns a value. In your case that value is being assigned to objUser.Email.
You have accidentally, used comparison operator instead of assignment operator.
objUser.Email == (Information.IsDBNull(drow("Email")) ? "" : drow("Email"));
should be, as you are not doing comparision, its an assignment.
objUser.Email = (Information.IsDBNull(drow("Email")) ? "" : drow("Email"));
You're using equal operator instead of assignment operator in the C# variant.
Change the == to = since what you want is assignment.
objUser.Email = (Information.IsDBNull(drow("Email")) ? "" : drow("Email"));
Try this:
objUser.Email = (DBNull.Value == drow("Email")) ? "" : drow("Email"));
See the Documentation for DbNull - where you will find examples:
From MSDN
private string AddFieldValue(string label, DataRow row,
string fieldName)
{
if (! DBNull.Value.Equals(row[fieldName]))
return (string) row[fieldName] + " ";
else
return String.Empty;
}