How to default null session values to blank strings in C# - c#

I'm used to using VB.net for web programming.
Often, I have something like:
Dim s as string = Session("s")
I get a string value for s from the web session. If there is no value in the web session, I get a blank string.
However, AFAIK, in C#, I have to have something like the code below to do the same thing.
string s;
try { s = Session["s"].ToString(); }
catch { s = ""; }
Is there an easier way to do this?

This is a quick way of doing this:
s = (string)Session["s"] ?? "";
This will cast Session["s"] to a string, and if it is not null, return the value. If it is null, it will return an empty string. The "a ?? b" expression is essentially the same as "a != null ? a:b" (?? is compiled more efficiently though)
Something else to keep in mind: you should never use exceptions for normal application logic.

Because string is reference type then is nullable, so you can check for empty or null by means of string.IsNullOrEmpty(s):
string s = string.IsNullOrEmpty((string)strObject) ? string.Empty : strObject.ToString();
Otherwise (as Philippe Leybaert says) you can use ?? operator.

I almost agree to Philippe, but it only works if "s" is present in the session, otherwise there will be a KeyNotFoundException. This code checks it, but does not solve the NULL issue of Philippe.
s= Session.ContainsKey("s")?Session["s"]:"";
So to cover both possibilities, it becomes mre complex:
s = Session.ContainsKey("s")?(Session["s"]??""):"";
It does not really make it easier, but the performance should be better than catching an exception.

Related

How to recognize a null sting

I have a string TempDayValues[j] that holds a null value but the following two examples do not recognize the null
string Temp = TempDayValues[j].Trim();
if (string.IsNullOrEmpty(Temp))
{
Console.WriteLine("Found Null");
TempDayValues[j] = TempDayValues[j - 1];
}
If(Temp == null)
{
//code here
}
Is there any better way to recognize null values?
Comparing with null is the way to check for it. However in your code, if you have not gotten already a NullReferenceException when calling Trim then your string is not null.
Might be that you are looking for IsNullOrWhiteSpace:
if (string.IsNullOrWhiteSpace(TempDayValues[j]))
{
Console.WriteLine("Found Null");
TempDayValues[j] = TempDayValues[j - 1];
}
If you first want to check if it is null and have one behavior and a different if it is empty/white space:
if(TempDayValues[j] == null)
{
// code
}
else if(TempDayValues[j].Trim() == string.Empty)
{
// code
}
Your question, while valid, is missing an explanation of what you're trying to accomplish. Since you've only asked about null checking; my answer only focuses on the null checking that is performed in your code snippet.
There are a few things to remark about your code that I think will help you understand the situation better.
String Temp = TempDayValues[j].Trim();
It's interesting to see that you have already called .Trim() on the string. If TempDayValues[j] was null, this would throw an exception. You can't call methods on null values (you also can't access properties and fields on a null value).
If your application is not throwing an exception; which I assume it is not as you have not mentioned it; then you have implicitly already "proven" that your string is not null. Because you would get an exception otherwise.
Also note that .Trim() will never make something null. Since you are only interested in checking if TempDayValues[j] is null (and potentially overwriting the value, but never using the value); it is functionally irrelevant to use .Trim() for the purpose of null checking.
Let's assume for the rest of the explanation that it is possible for your string to be null; even though .Trim() has made it impossible in your example.
if (string.IsNullOrEmpty(Temp))
{
Console.WriteLine("Found Null");
TempDayValues[j] = TempDayValues[j - 1];
}
Your if block will be executed if your string is null, but also if it is empty. You are, after all, calling the method string.IsNullOrEmpty(). An empty string is a string that is not null, but also does not contain any characters.
So a more correct message would be "found null or empty string".
if(Temp == null)
{
//code here
}
While this is a valid method of checking for null; the if block will not execute if your string is empty. This might be what you are looking for. In most cases, I would expect String.IsNullOrEmpty() to be more suited; but I'm not aware of the specific purpose of your code.
Here, it would be correct to say that you "found null" and NOT an empty string.
That being said; what is the answer to this problem?
This isn't easy to answer; as you've not explained the intention of the code snippet. I am going to offer a code improvement, it's the best I can give you without more info.
string Temp = TempDayValues[j];
if (string.IsNullOrEmpty(Temp)) //use Temp == null here if you don't want it to trigger on empty strings.
{
Console.WriteLine("Found Null or empty string");
TempDayValues[j] = TempDayValues[j - 1];
}
edit If you also need this if block to be executed for cases where your string is not null, not empty, but it only contains whitespaces; then it is relevant to call .Trim(). In that case, change your if block to:
if (string.IsNullOrEmpty(Temp) || string.IsNullOrEmpty(Temp.Trim()))
If Temp is null, only the left operand will be executed (because it makes the evaluation result true regardless of the right operand).
The right operand will be executed only if your string is not already null or empty. In that case, it allows you to check for a string that contains only whitespace characters.

C# Best Practice - What is the best practice when converting int? to int

I have a nullable int coming in from the database from a stored procedure that I know will not have a null value. I have done the bellow:
public List<EngineerDetails> GetCarouselEngineerDetailsList(int customerID)
{
using (var db = new MainEntities80())
{
var foo0= db.procedure().Select(s => new fooo()
{
foo= s.foo,
foo2 = s.foo2,
foo3 = s.foo3 ,
foo4 = s.foo4 ,
x = s.CurrentJobId.Value
}).ToList();
return foo0;
}
}
But I wanted to know although I know that the value will always be there. Is it good practice to check before getting the value. Maybe with a turnary expression.
Or because we know it will not be null should we forget about the check?
An InvalidOperationException will be thrown if s.CurrentJobId is actually null anyway. That's almost always the best outcome for situations of "the world is not the way I expect it to be" so it makes sense to use the code exactly as-is.
if (s.CurrentJobID.HasValue)
{
CurrentJobID = s.CurrentJobID.Value
}
You could do it like this:
int result = s.CurrentJobId?? Int32.MinValue;
This will make sure that the value of x is assigned to result, but if s.CurrentJobId is null, Int32.MinValue will be assigned to it.
It will prevent an exception to be thrown, and you can verify afterwards if it was null anyway by checking on Int32.MinValue.
However, if the value should indeed never be null, it is a better option for an exception to be thrown and fail fast.
You can use CurrentJobID = s.CurrentJobID.GetValueOrDefault().
If NULL is encountered then this will produce the default value for the underlying type, which for numbers is always 0.
Or if you'd rather have an 'exceptional' value such as -1, then you can do so with CurrentJobID = s.CurrentJobID.GetValueOrDefault(-1).

OracleDataReader - Handling a NULL field value when setting up a default dropdown SelectedValue

I've got the following code:
// Here is where we will read in all our values and populate the form with them
lblBenCatX.Text = Convert.ToString(reader["Category"]);
lblBenProvX.Text = Convert.ToString(reader["Provision"]);
txtCommentBox.Text = Convert.ToString(reader["Feedback"]);
ddlDefect1.SelectedValue = Convert.ToString(reader["Network"]);
ddlIssue1.SelectedValue = Convert.ToString(reader["Issue_ID"]);
ddlResolution1.SelectedValue = Convert.ToString(reader["Resolution_ID"]);
ddlDefect2.SelectedValue = Convert.ToString(reader["Network2"]);
ddlIssue2.SelectedValue = Convert.ToString(reader["Issue_ID2"]);
ddlResolution2.SelectedValue = Convert.ToString(reader["Resolution_ID2"]);
The first 3 rows of code; no problem. However, if I have a record with a NULL value, the dropdowns break the code. So, I'm thinking I need to check the field first to make sure it's not NULL. Something like:
if (!Convert.ToString(reader["Network"]) = NULL)
{
ddlDefect1.SelectedValue = Convert.ToString(reader["Network"]);
}
However, that's giving me an error:
The left-hand side of an assignment must be a variable, property or
indexer
Any ideas? This is C# in VS2015 with an Oracle back end, if any of that matters.
In C#, you need to use two equal signs in a row == for equality comparison, not one. One equal sign = is an assignment operator.
if (first == second) { ... }
In your case, though, you would want to use the "not equals" != operator:
if (Convert.ToString(reader["Network"]) != null)
Which is cleaner and slightly more-efficent than this:
if (!(Convert.ToString(reader["Network"]) == null))
Note that I've wrapped the whole inner comparison in parens so the whole statement is being negated; otherwise, it will think you're trying to say !Convert.ToString(reader["Network"]), and, as you pointed out in the comments here, you can't use ! with a string.
That being said, if you're converting to string, then it's better to use string.IsNullOrEmpty() for checking:
if (!string.IsNullOrEmpty(reader["Network"].ToString())))
But the best is probably to just check if the column value is null, rather than converting it to string:
if (!reader.IsDBNull(["Network"]))
= is an assignment operator, used when setting values.
== is an equality operator, which determines whether something is equal to something else.
!= is also an equality operator, opposite to the one above. So, when something is not equal to something else.
So actually, you should be using != in this scenario:
if (Convert.ToString(reader["Network"]) != null)
{
ddlDefect1.SelectedValue = Convert.ToString(reader["Network"]);
}
You have a couple of choices. The first is to check if the value is DBNull which is different than an empty string/null value.
if (!reader.IsDBNull([ordinalPositionOfNetworkInSelectStatement]))
ddlDefect1.SelectedValue = Convert.ToString(reader["Network"]);
See IDataReader.IsDBNull. The only thing is that you need to know the ordinal position of the column you are checking.
The alternative is to check for dbnull in your sql select statement and use a function to return an empty string if it is. The positive side of this approach is you do not have to worry about checking for null in your c# code but I am not sure if it has any negative consequences in your oracle query or view. You can do this with COALESCE.
SELECT Category, Provision, Feedback, COALESCE(Network, '') AS Network /*other columns*/
FROM ... -- rest of the query
disclaimer - my oracle syntax is lacking but COALESCE does exist as a function

Correct syntax for trapping NULL values

My C# code-behind looks like this:
if ((DT["BENEFIT_TYPE1"].Equals(0)))
{ DropDownList_Tracking_BenefitType1.SelectedValue = null; }
else if ((DT["BENEFIT_TYPE1"].ToString() = "" ))
{ DropDownList_Tracking_BenefitType1.SelectedValue = null; }
else
{DropDownList_Tracking_BenefitType1.SelectedValue = (DT["BENEFIT_TYPE1"].ToString());}
The code doesn't like the "else if" line; everything inside the parens is underlined in red. When I hover my mouse over it, the popup message is:
The left-hand side of an assignment must be a variable, property or
indexer
Can someone tell me how to fix this? I'm trying to account for NULL values in my dataset.
As Juan pointed out, you need ==, however note that NULL and "" are different things.
You can check for null or empty with:
else if (string.IsNullOrEmpty(DT["BENEFIT_TYPE1"].ToString()))
You are missing a '=' character. In C# comparisions are done with double equal sign '=='. A single one means assignment, hence your error as you cannot assign in a if statement.
Try:
(DT["BENEFIT_TYPE1"].ToString() == "" ))
As other have suggested there are other things to take into account here.
For checking strings to be null or empty you can use the following:
string.IsNullOrEmpty(yourString)
Or if you treat empty space string as empty
string.IsNullOrWhitespace(yourString)
If DT is a datatable that you are sourcing from Database the nulls in database are not null or empty string but DbNull, so you should compare this way:
DT["field"] == DbNull.Value
Or
DT.IsNull("field")

Trim Textbox value by considering NULL

Can you tell me if TrimNull() is redundant and if I should be using an alternative?
For example:
string username = UsernameTextBox.Text.TrimNull();
I am told there is no definition or extension method. Perhaps there is a reference I am missing?
UPDATE:
What is the most readable way to return empty string if the value is NULL?
There's no such function as TrimNull(String) - it wouldn't do anything. A string is either a null or not null, it can't contain a mixture of both. If the string were null, a static function TrimNull(myString) would not be able to 'remove' anything from the string. If it weren't null, there would be no NULL to remove. Even worse, if TrimNull were an instance method myString.TrimNull() would simply cause an exception if myString were NULL - because you cannot invoke any method on a null reference.
If your goal is to trim whitespace characters surrounding the string, just use myString.Trim().
If your goal is to detect whether the string is null, use myString == NULL
If your goal is to detect whether the string is empty or null use String.IsNullOrEmpty(myString)
If your goal is to trim trailing null characters (\0) from data stream, try the following:
myString.TrimEnd(new char[] { '\0' } )
But as Frédéric Hamidi said, if you're referring to the latter, the user will have a hard time getting null characters into a TextBox, so you shouldn't worry about that scenario in your processing of their input.
I usually use String.IsNullOrWhiteSpace(), like this:
string username = (String.IsNullOrWhiteSpace(UsernameTextBox.Text) ?
null : UsernameTextBox.Text.Trim());
That way, if the .Text property is null, it doesn't cause an exception.
You could create your own extension-method for that, if you like:
public static class StringExtensions
{
public static string TrimNull(this string value)
{
return string.IsNullOrWhiteSpace(value) ? value : value.Trim();
}
}
Add this to your project and your code will work.
This is just an alternative.
Use null-coalescing operator as mentioned in #sixlettervariables answer in Negate the null-coalescing operator
string username = (UsernameTextBox.Text ?? String.Empty).Trim();
A string being NULL is not its value. its a state. It means it has not been assigned a memory (coz its a reference type). Had it been a value type datatype it woudld be assigned a default value automatically like for int its 0 and so on
u should use
if(!String.IsNullOrEmpty(UsernameTextBox.Text))
string username = UsernameTextBox.Text.Trim();

Categories

Resources