Object reference not set to an instance of an object - c#

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

Related

Check if child object value exists NullReferenceException

I'm pretty new to C#. While attempting to set a local variable value, I'm running into a NullReferenceException.
It appears that the Buyer object is null, which I'm assuming is why it can't figure out the Buyer.Username value. What I'm not sure about is how to check if Buyer is not null AND that the Buyer.Username has a non-null value (in the most simple way possible). Unfortunately, I'm using C# 7.3 which doesn't appear to have support for the ?? operator.
BuyerUserName = string.IsNullOrEmpty(model.Transactions[i].Buyer.Username) ? "" : model.Transactions[i].Buyer.Username
Both ?? and ?. were introduced in C# 6, so you can use them:
BuyerUserName = model.Transactions[i].Buyer?.Username ?? string.Empty;
But even without that, there is nothing wrong with taking more than one line to do something, and you could just use an if statement:
var buyer = model.Transactions[i].Buyer;
if (buyer != null && buyer.Username != null)
BuyerUserName = buyer.Username;
else
BuyerUserName = string.Empty;

Validating null value from DataTable row

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

Nulling a string or any type when don't know return value?

What is the best way to null a item if you don't know what its value can be? I am going through objects which can be of any type from an object. How can I cast when I don't know what the return value might be?
string viewValue
= emop.Object[null, viewDetails.Columns[i].Property] != null
? emop.Object[null, viewDetails.Columns[i].Property].Value.ToString()
: string.Empty;
I thought it might be better to cast all the objects as string but some items it's failing on saying item is null.
Without approving of your conversion to a string for all objects, since I don't know the data you're working on. I believe this would fix your actual error.
string viewValue
= emop.Object[null, viewDetails.Columns[i].Property] != null && emop.Object[null, viewDetails.Columns[i].Property].Value != null
? emop.Object[null, viewDetails.Columns[i].Property].Value.ToString()
: string.Empty;
I added a not null check against the .Value property. Otherwise calling .ToString() could be calling against a null object.

DataTable; Object reference not set to an instance of an object

I have the following line of code,
sitetb.Text = sitesformdataset.Tables["Sites"].Rows[_selectedindex].Field<string>("SiteName").ToString();
This returns the
System.NullReferenceException; Object reference not set to an instance
of an object.
I know why it is returning this exception and thats because there is nothing in that cell.
How do I correctly handle this?
try
if(sitesformdataset!=null&&sitesformdataset.Tables["Sites"]!=null)
{
sitetb.Text = sitesformdataset.Tables["Sites"].Rows[_selectedindex].Field<string>("SiteName").ToString();
}
You don't need to call .ToString()
.Field<string>("SiteName") convert to string , you don't need to call tostring again.
sitetb.Text = sitesformdataset.Tables["Sites"].Rows[_selectedindex].Field<string>("SiteName");
if your cell value null then you can't call ToString method of null object, that will fail.
If you have already checked for _selectedindex != -1 and being in the correct range the correct the code like this:
sitetb.Text = (sitesformdataset.Tables["Sites"].Rows[_selectedindex].Field<string>("SiteName")?? "").ToString();
it is the short writing of this:
var cellContetnt = sitesformdataset.Tables["Sites"].Rows[_selectedindex].Field<string>("SiteName");
if(cellCount == null)
sitetb.Text = "";
else
sitetb.Text = cellContent.ToString();

how can I check whether the session is exist or with empty value or null in .net c#

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

Categories