how to convert the sign "?" in c# to vb.net? - c#

I am trying to convert c# code to vb.net but I have difficulties in converting the sign "?" in c# to vb.net. here my code to convert
public audit_trail Mapper(IDataReader rdr)
{
audit_trail audit_trail = new audit_trail();
audit_trail.Log_id = rdr["Log_id"] is DBNull ? 0 : (int)rdr["Log_id"];
audit_trail.Host = rdr["Host"] is DBNull ? string.Empty : (string)rdr["Host"];
return audit_trail;
}
how to convert the sign "?" to vb.net??
I would like to convert
audit_trail.Host = rdr["Host"] is DBNull ? string.Empty : (string)rdr["Host"];
to something like
if rdr["Host"] is DBNull.Value then
audit_trail.Host = string.Empty
else
audit_trail.Host = rdr["Host"]
end if
but the code is too long, too many line of code.. do you guys have an idea to convert to the short one?

The visual basic syntax for the ternary operator is If([condition,] op1, op2).

audit_trail.Host = If(IsDBNull(rdr("Host")), String.Empty, CType(rdr("Host"), String))

Related

DataTable checking if null returns an error but not on variable declaration

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 there a shorthand for the ternary operator in C#?

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.

vb.net to c# conversion for IsDBNull not working

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;
}

How do I convert a database number to hex when the field might be null?

I have trouble to convert from decimal to hex.
Here is my code:
select new
{
MessageID = table1.Field<Int32?>("MessageID"),
MessageIDHex = (String)table1.Field<Int32>("MessageID").ToString("X")
}
It gives me Error
with DBNUll.Value cant not change to System.In32
So I have tried
MessageIDHex= (String)table1.Field<Int32?>("MessageID").ToString("X")}
but it gives me another error.
How can I fix it or it does have another way to solve it.
Apparently, MessageID can be DBNull. The simplest solution is to read the value as a nullable int (to prevent the conversion error from occurring). If you use Field with a nullable type, DBNull is automatically converted to null, which can then be coerced to 0 with the ?? operator:
MessageIDHex = (table1.Field<Int32?>("MessageID") ?? 0).ToString("X")
Alternatively, if you prefer, you can have DBNull values in the database result in an empty or a null string for MessageIDHex:
MessageIDHex = table1.IsNull("MessageID") ? "" : table1.Field<Int32>("MessageID").ToString("X")
MessageIDHex = table1.IsNull("MessageID") ? null : table1.Field<Int32>("MessageID").ToString("X")

Conditional variables

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();

Categories