I have a simple string variable like:
var currentMedianEmployeeProgressToBackcheck = "";
and I fill it like:
var EmployeeMedian = (from DataRow dr in dtEmployeeMedian.Rows
select new
{
MedianEmployeeProgressToBackcheck = dr["MedianEmployeeProgressToBackcheck"]
}).FirstOrDefault();
currentMedianEmployeeProgressToBackcheck = EmployeeMedian.MedianEmployeeProgressToBackcheck.ToString();
But when it comes null it throw an exception of null:
System.NullReferenceException: 'Object reference not set to an
instance of an object.'
EmployeeMedian was null.
How can I validate that null variable before execute it? Regards
I try with simple if like:
if (EmployeeMedian.MedianEmployeeProgressToBackcheck != null){}
but it don't works
You can use Null propagation operator if it's C# 6 or above like below which makes sure to only do the operation if the instance is not null:
currentMedianEmployeeProgressToBackcheck = EmployeeMedian?.MedianEmployeeProgressToBackcheck?.ToString();
otherwise you will need to put an if condition before accessing those to make sure you are not calling it on a null reference like:
if(EmployeeMedian !=null && EmployeeMedian.MedianEmployeeProgressToBackcheck != null)
{
currentMedianEmployeeProgressToBackcheck = EmployeeMedian.MedianEmployeeProgressToBackcheck.ToString();
}
Related
I am trying to get the list of items inside of a quickbooks database. I have the following snippet of code:
IItemServiceRet itemServiceRet = itemRet.ItemServiceRet;
TestItem item = new TestItem();
item.Name = itemServiceRet.Name.GetValue();
item.Desc = itemServiceRet.ORSalesPurchase.SalesOrPurchase.Desc.GetValue();
item.Rate = itemServiceRet.ORSalesPurchase.SalesOrPurchase.ORPrice.Price.GetValue().ToString();
item.ItemType = "Service";
item.QBID = itemServiceRet.ListID.GetValue();
item.EditSeq = itemServiceRet.EditSequence.GetValue();
The code fails on the line:
item.Desc = itemServiceRet.ORSalesPurchase.SalesOrPurchase.Desc.GetValue();
"Object reference not set to an instance of an object"
Because that particular service item in the QB database does not have a description. I was curious if there was a 'clean' way to check for null values without having to have each line include an if statement checking if GetValue() returns null?
Edit: After trying Andrew Cooper's solution of:
item.Desc = itemServiceRet.ORSalesPurchase.SalesOrPurchase.Desc == null ? null : itemServiceRet.ORSalesPurchase.SalesOrPurchase.Desc.GetValue();
It still throws the exception:
Object reference not set to an instance of an object
Its as if GetValue() returns nothing at all if there is no description, which wouldn't make much sense.
You could use the ternary operator like this:
item.Desc = itemServiceRet.ORSalesPurchase.SalesOrPurchase.Desc == null ? null : itemServiceRet.ORSalesPurchase.SalesOrPurchase.Desc.GetValue();
But that's pretty ugly.
Best bet is to create a helper method that takes whatever type Desc and wraps the above logic.
I don't think there's any better solution, as you can't access the functions of a null object. I typically create a constructor for my items that does the checking so I only have to do that once. So in your example:
TestItem item = new TestItem(itemRet.ItemServiceRet);
The constructor would look like this:
public TestItem(IItemServiceRet i)
{
if(i.Name != null) this.Name = i.Name.GetValue();
if(i.ORSalesPurchase != null)
if(i.ORSalesPurchase.SalesOrPurchase != null)
{
if(i.ORSalesPurchase.SalesOrPurchase.Desc != null) this.Desc = i.ORSalesPurchase.SalesOrPurchase.Desc.GetValue();
if(i.ORSalesPurchase.SalesOrPurchase.ORPrice != null)
if(i.ORSalesPurchase.SalesOrPurchase.ORPrice.Price != null) this.Price = i.ORSalesPurchase.SalesOrPurchase.ORPrice.Price.GetValue();
}
}Keep in mind that this does work well for strings, as an empty string is usually the same as a blank field, but for number fields in QuickBooks this may cause problems. For example, an Invoice line can have a blank quantity field (which is a double). A double will default to the value of 0.0, but a blank quantity field in QuickBooks is treated as a quantity of 1.0. This can also cause problems with dates, as QuickBooks can have null date fields.
I am getting error:
Object reference not set to an instance of an object.
It errors when I try to get the value of a session. The value of the session is null but I have tried testing it to check if it is null and on the if statement it still always fails with this error.
string test;
if (Session["CustType"].ToString() != null ||
Session["CustType"].ToString() != String.Empty)
{
test = Session["CustType"].ToString();
txtCustomerType.Text = test;
}
The error is on the second line of this code. I just don't know what to do because I can't do anything with it if it just errors even when I tried to check whether it is empty or not.
You need to check following. Remove ToString() as calling ToString() on null gives you Object reference error.
Session["CustType"] != null
Use
(!String.IsNullOrEmpty(Session["CustType"]))
first check null, and then call ToString
var obj = Session["CustType"];
if (obj != null &&
!string.IsNullOrEmpty(obj.ToString()))
{
txtCustomerType.Text = obj.ToString();
}
To use ToString() on an object, it cannot be null. Where you have..
Session["CustType"].ToString() != null
You need to replace it with...
Session["CustType"] != null
It may be because you are referencing an object in a table that cannot be reached. Debug your code with breakpoints and check whether your test variable has a value assigned to it at the moment of the exception. If the count of the held table is 0, this will confirm that is the problem.
You should check:
Session["CustType"] != null
before using Session["CustType"].ToString() because if it is null, you are trying to call ToString() on null object.
Most concise code would be probably:
var test = Session["CustType"] as string;
if (!string.IsNullOrEmpty(test))
{
txtCustomerType.Text = test;
}
you have remove tostring() from session while checking null value
use this
if (Session["CustType"] != null &&
Session["CustType"].ToString() != string.Empty)
instead
if (Session["CustType"].ToString() != null &&
Session["CustType"].ToString() != String.Empty)
if (System.Web.HttpContext.Current.Request.Form[day].ToString() != null)
{
var test = System.Web.HttpContext.Current.Request.Form[day].ToString();
}
I have written these lines but when Form[day] doesn't contain any value, it gives an null object exception. How can I solve this ?
You have to check this value before access it. For example, like this:
var form = System.Web.HttpContext.Current.Request.Form;
if (form != null && !String.IsNullOrEmpty(day) && form.AllKeys.Contains(day))
{
var test = form[day].ToString();
}
Does anyone know how can I check whether a session is empty or null in .net c# web-applications?
Example:
I have the following code:
ixCardType.SelectedValue = Session["ixCardType"].ToString();
It's always display me error for Session["ixCardType"] (error message: Object reference not set to an instance of an object). Anyway I can check the session before go to the .ToString() ??
Something as simple as an 'if' should work.
if(Session["ixCardType"] != null)
ixCardType.SelectedValue = Session["ixCardType"].ToString();
Or something like this if you want the empty string when the session value is null:
ixCardType.SelectedValue = Session["ixCardType"] == null? "" : Session["ixCardType"].ToString();
Cast the object using the as operator, which returns null if the value fails to cast to the desired class type, or if it's null itself.
string value = Session["ixCardType"] as string;
if (String.IsNullOrEmpty(value))
{
// null or empty
}
You can assign the result to a variable, and test it for null/empty prior to calling ToString():
var cardType = Session["ixCardType"];
if (cardType != null)
{
ixCardType.SelectedValue = cardType.ToString();
}
Getting this error on this code:
string pname = null;
pname = ag.FirstOrDefault().arrangement.parent.name;
when calling the line pname = ag.FirstOrDefault.....
The filed parent.name is empty(null), which is fine I want to get an empty(null) string in such case.
How can I get rid of the error?
Either ag is null, the FirstOrDefault call is returning null, arrangement is null, or parent is null.
Only you are in a position to determine which one of those is actually the culprit.
If the property ag.FirstOrDefault().arrangement.parent.name is null it means the object ag is null also. This is the reason you are getting object reference error.
The answer Leons provided is actually what I was going to suggest. You need to do some research on the problem its one of the simplest thing to avoid ( trying to reference a null object ) in programming.
You cannot access the properties of a null object. If ag.FirstOrDefault() will return null, then you will not be able to access arrangement.
var temp = ag.FirstOrDefault();
string pname = (temp!= null) ? temp.arrangement.parent.name : null;
You may need to do further null checking.
try
var obj = ag.FirstOrDefault();
if( obj !=null)
pname = obj.arrangement.parent.name ?? String.Empty;
or you can try
//This will set the variable to null:
var obj = ag.FirstOrDefault();
if( obj !=null)
pname = Convert.ToString(obj.arrangement.parent.name);
Note : ag.FirstOrDefault().arrangement.parent.name is nullable type