Check object null or not [duplicate] - c#

This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 7 years ago.
I wanted to check if User exists or not in the database, and i take a User object and check if it is null or not.But the problem is in my code if user doen't exist in our database it returns following exception,
Object reference not set to an instance of an object.
I know this error happen when there is no such a user in our database.So.. i wanted to know if this user object( i want to return null or not) null or not.
My Part of Code
if(newsManager.GetUserUsingEmail(User.Email).Email != null) //If user doesn't exists this come the above mentioned exception
{
//User Exists
}
else
{
//User Doesn't exists
}
How to solve it ?

The null reference exception is probably due to you trying to access the Email property on the user returned from the GetUserUsingEmail method. You should test if the returned value is null first and only then try accessing properties on it.
var user = newsManager.GetUserUsingEmail(User.Email);
if (user != null)
{
// user exists
}
else
{
// user does not exist
}

if newsManager.GetUserUsingEmail(User.Email) returns null, then you will agree that attempting to invoke .Email should give you the Object reference not set to an instance of an object. error, right?
As suggested in the comments, if your condition is truly just checking to see if the user exists or not, then simply do this:
if(newsManager.GetUserUsingEmail(User.Email) != null) //If user doesn't exists this come the above mentioned exception
{
//User Exists
}
else
{
//User Doesn't exists
}
If, as your code suggests, your intent is really to enter the if block only if you have a valid Email value for a valid user, then you can do that like this instead:
var user = newsManager.GetUserUsingEmail(User.Email);
if(user != null && !string.IsNullOrEmpty(user.Email))
{
//User Exists and has a valid email
}
else
{
//User Doesn't exists or doesn't have a valid email.
}

You cannot get property from null. Check object != null instead:
if(newsManager.GetUserUsingEmail(User.Email) != null) //If user doesn't exists this come the above mentioned exception
{
//User Exists
}
else
{
//User Doesn't exists
}
In C# 6.0 you can use Safe Navigation Operator (?.):
if(newsManager.GetUserUsingEmail(User.Email)?.Email != null) //If user doesn't exists this come the above mentioned exception
{
//User Exists
}
else
{
//User Doesn't exists
}

Related

Why is this null check incurring a null dereference error?

So basically I want to check that a setting is not set in my C# application. The code here
if (Default["StudentAccountTypeDefault"] is null) // Crashes after this
{
//
}
else
{
//
}
seems to be crashing on the null-check. I've put a breakpoint there, and it shows Default["DefaultStudentAccountType"] to just be a blank string. Why is it crashing with a NullReferenceException? I'm pretty sure this is where it crashes-if I comment out if statement it works as expected.
Edit: To alleviate some confusion. Sooooo, Default is actually Settings.Default, and to add to that, I was actually trying to access it inside the Settings() constructor. So, before it had been initialized, obviously. Oops. "Full"-er code below.
public Settings() {
// // To add event handlers for saving and changing settings, uncomment the lines below:
//
// this.SettingChanging += this.SettingChangingEventHandler;
//
// this.SettingsSaving += this.SettingsSavingEventHandler;
//
if (Settings.Default["DefaultStudentAccountType"] is null)
{
}
else
{
}
}
You should be checking with == not with is, also depending on your data type you may need to check if Default is null too. Try this:
if(Default == null || Default["StudentAccountTypeDefault"] == null)
{
}
else
{
}
Default is a variable, so if it is null, accessing the indexer ["StudentAccountTypeDefault"] will throw a null reference exception.
If you're using a new enough .NET version, you can use:
if (Default?["StudentAccountTypeDefault"] is null)
(the null-coalescing operator). Otherwise, just check Default for null before using its indexer.

Asp.net Handling duplicate key exception

I am trying to handle duplicate key exception in detailsview, and my code under iteminserted is:
if (e.Exception.Message.Contains("duplicate key")
{
Response.Write("Student already registered!");
e.ExceptionHandled = true;
}
The code is running correctly when there is duplicate key, but in normal situation (no duplicate key) it gives following error:
‫System.NullReferenceException: Object reference not set to an instance of an object
Check if it is null before running the If statement.
if (e.Exception.Message != null){
if (e.Exception.Message.Contains("duplicate key")
{
Response.Write("Student already registered!");
e.ExceptionHandled = true;
}
}

Null reference Exception unhandled by the user code

I build my solution in visual studio(successfull) and I am trying to run it but for some reason at the following line of code it was throwing the exception I went several articles but there was no exact solution how this could be handled
public static int GetCurrentPolicyClassId()
{
**int policyClassId = (int) HttpContext.Current.Session[AppConstants.SK_POLICYCLASSID];**
return policyClassId;
}
One of the values in the chain you've called is null. You just need to check before getting the values:
if(HttpContext != null &&
HttpContext.Current != null &&
HttpContext.Current.Session != null &&
HttpContext.Current.Session[AppConstants.SK_POLICYCLASSID] != null)
{
// Get the value here.
}
else
{
// Something was null. Either set a default value or throw an Exception
}
You should probably check if HttpContext != null && HttpContext.Current != null && HttpContext.Current.Session != null
any exception is handled by try/catch (or finally), if that exception is possible to handle in general.
For example StackOverflowException could not be handled.
You need to:
what type of exception is
understand reasons of it
based on this decide if that exception is an exceptional behaviour in your application
if yes, handle it with try/catch if program needs to handle it, or leav program to fail, as the exception recieved is too dangerous and it's better to let to fail everything.
if this is not exceptional behavior, try to handle it with, for example null checks, or whatever...
Hope this helps.

Cache == null? Is it possible?

Is it legal to make the following statement:
if(Cache[CACHE_KEY] == null)
{
//do something to form cache
}
else
{
//do something else that uses cache
}
I'm not sure my program is actually functioning properly (even though it compiles) and am wondering if a cache doesn't exist is it set to null?
Yes, that is legal (but the question in the title is not, see below for details).
Though, it may be wise to check that the type in the cache is what you're expecting rather than having to do this check twice, such as:
//in English, the following line of code might read:
// if the item known in the cache by the specified key is in
// in fact of type MyExpectedReferenceType, then give me it
// as such otherwise, give me a null reference instead...
var myCachedInstance = Cache[key] as MyExpectedReferenceType;
if (myCachedInstance == null)
{
//we retrieved a reference to an instance of an MyExpectedReferenceType
}
else
{
//oh, no - we didn't!
}
On re-reading your question though, and thinking about your program not working properly, I'm tempted to say you have bigger issues than this; how is your program not working correctly? The Cache instance itself will never be null while accessible - it is a read-only field of Page. However, your expected cached value could be null and, if this is the problem, you should be receiving a NullReferenceException - is that the case?
UPDATE:
To address your comment, check out the comments I added to the code.
Very much legal; rather its better to check for a value before performing action, especially to make sure that key has not slided-out, or expired, etc.
There is a potential race condition in the code you posted:
if(Cache[CACHE_KEY] == null)
{
//do something to form cache
}
else
{
// Another thread could have removed CACHE_KEY from the Cache before you get here
}
It's better to first extract the object from the cache, then test it for null, e.g.:
MyObject cachedObject = Cache[CACHE_KEY] as MyObject;
// or MyObject cachedObject = (MyObject) Cache[CACHE_KEY]; if you know it is of type MyObject
if(cachedObject == null)
{
cachedObject = ... // generate the cached object
Cache.Insert(CACHE_KEY, cachedObject, ...);
}
// use cachedObject
Yes it`s possible, Cache will always be initialize (like session and application obj)
But you can check if a key in the cache is null

Which is correct way to check for Null exception?

Which is the most correct code?
if (HttpContext.Current.Response.Cookies[authCookieName] != null) {
HttpContext.Current.Response.Cookies[authCookieName].Value = "New Value";
}
or
if (HttpContext.Current != null)
if (HttpContext.Current.Response != null)
if (HttpContext.Current.Response.Cookies != null)
if (HttpContext.Current.Response.Cookies[authCookieName] != null)
HttpContext.Current.Response.Cookies[authCookieName].Value = "New Value";
If any one of HttpContext, HttpContext.Current, HttpContext.Current.Response, or Http.Current.Response.Cookies is null, you're already in trouble. Let the exception happen and fix your web server.
Both are good. Assuming that you have already checked everything else that need to be checked first. E.g.:
private bool CheckSuspendersAndBelt()
{
try
{
//ensure that true is true...
if (true == true)
{
//...and that false is false...
if (false == false)
{
//...and that true and false are not equal...
if (false != true)
{
//don't proceed if we don't have at least one processor
if (System.Environment.ProcessorCount > 0)
{
//and if there is no system directory then something is wrong
if (System.Environment.SystemDirectory != null)
{
//hopefully the code is running under some version of the CLR...
if (System.Environment.Version != null)
{
//we don't want to proceed if we're not in a process...
if (System.Diagnostics.Process.GetCurrentProcess() != null)
{
//and code running without a thread would not be good...
if (System.Threading.Thread.CurrentThread != null)
{
//finally, make sure instantiating an object really results in an object...
if (typeof(System.Object) == (new System.Object()).GetType())
{
//good to go
return true;
}
}
}
}
}
}
}
}
}
return false;
}
catch
{
return false;
}
}
(sorry, couldn't resist... :) )
could try:
if(HttpContext.Current != null &&
HttpContext.Current.Response != null &&
HttpContext.Current.Response.Cookies != null &&
HttpContext.Current.Response.Cookies[authCookieName] != null)
{
// do your thing
}
HttpContext.Current.Response.Cookies will never be null. The only thing that can cause a null is if the cookie you are expecting doesn't exist, so the first is correct. HttpContext.Current would be null if you weren't accepting a web request though :)
The first example you gave is more than enough. Like mentioned, if any of the other objects are null there is a problem with ASP.NET.
if (HttpContext.Current.Response.Cookies[authCookieName] != null) {
HttpContext.Current.Response.Cookies[authCookieName].Value = "New Value";
}
But rather than littering your code with these often many checks, you should create some generic functions like SetCookie, GetCookie, GetQueryString, and GetForm, etc. which accept the name and value (for Set functions) as parameters, handle the null check, and returns the value or an empty string (for Get Functions). This will make your code much easier to maintain and possibly improve, and if you decide to use something other than Cookies to store/retrieve options in the future, you'll only have to change the functions.
Neither is really more correct, though I would avoid the second, as deeply nested conditionals tend to be hard to understand and maintain.
If you would prefer you get a null pointer exception, use the first. If you want to deal with nulls in another way or silently, use the second (or a refactored version of the second).
If you think there's a chance that Current, Response, Cookies, or Cookies[authCookieName] could be null, and you have a reasonable thing to do if any of them are, then the latter's the way to go. If the chances are low, and/or there's nothing you can do if the intermediates are null, go for the former, as it's more concise - the best you could do is to get better logging if you use the expanded example.

Categories

Resources