Below is the code and the problematic line.
When I hover with the mouse on src.EnergyServiceLevel, it shows that it's null.
How can that be if I'm checking for null in the previous line?
My guess was that maybe there are threads that making the problem so I've add a lock,
but it didn't helped.
public static ServiceLevelsGroup SafeClone(this ServiceLevelsGroup src) {
ServiceLevelsGroup res = null;
lock (_locker) {
if (src != null) {
res = new ServiceLevelsGroup();
if (src.EnergyServiceLevel != null) {
res.EnergyServiceLevel = new ServiceLevelInfo { ServiceGrade = src.EnergyServiceLevel.ServiceGrade };
if (src.EnergyServiceLevel.Reason != null)
res.EnergyServiceLevel.Reason = src.EnergyServiceLevel.Reason;
}
}
}
return res;
}
The exception occurs at the res.EnergyServiceLevel = ... line in the above code.
Here's a screenshot of the exception occurring in debug mode:
Your code shows lock(_locker) - so it looks like you're in a multithreaded environment. Can you check that nothing else is NULLing your variable? i.e. that everything else is also calling lock(_locker) correctly?
Maybe your NULL is at res.EnergyServiceLevel.
src.EnergyServiceLevel.ServiceGrade may be null
Moving mouse pointer to each reference will exactly show you which is null.
Related
I have a problem resolving this CS8603 warning. Even though there is a null-check for resource variable, null reference is still possible. How come?
Code:
public string GetResource(string resourcePath)
{
var resource = Application.Current.Resources[resourcePath];
if (resource == null)
{
return $"{ResourceError} [{resourcePath}]";
}
// ToDo: CS8603
return resource.ToString();
}
You did correctly check wether resource is null. But even if it is not, ToString() might return null. You can use something like
return resource.ToString() ?? "";
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.
dbLinq XMlMappingSource.cs contains code:
public void ReadEmptyContent(XmlReader r, string name)
{
if (r.IsEmptyElement)
r.ReadStartElement(name, DbmlNamespace);
else
{
r.ReadStartElement(name, DbmlNamespace);
for (r.MoveToContent(); r.NodeType != XmlNodeType.EndElement; r.MoveToContent())
{
if (r.NamespaceURI != DbmlNamespace)
r.Skip();
throw UnexpectedItemError(r);
}
r.ReadEndElement();
}
}
This causes compile warning
Warning CS0162 Unreachable code detected
at line
for (r.MoveToContent(); r.NodeType != XmlNodeType.EndElement; r.MoveToContent())
( https://github.com/DbLinq/dblinq2007/blob/d7a05bb452b98fd24bca5693da01ecfecd4f3d40/src/DbLinq/Data/Linq/Mapping/XmlMappingSource.cs#L176 )
in third part of for clause r.MoveToContent()
It looks like normal node traversal code and third part of for is reached.
How to fix this ?
Using .NET 4
You never execute the increment step, because your first run through the loop always throws an exception.
As Rawling stated you are throwing the exception no matter what.
Try changing the loop to this:
for (r.MoveToContent(); r.NodeType != XmlNodeType.EndElement; r.MoveToContent())
{
if (r.NamespaceURI != DbmlNamespace)
r.Skip();
else
throw UnexpectedItemError(r);
}
This will fix your issue.
Having an odd problem. It's happened a few times over the years, but I've never been able to figure out why. Always solved it by rearranging the code I had in place, but would like to know is there's a more proper way of dealing with it, or at least figuring out what's behind it.
Non-working version:
public bool CaptureFrame(ArrayCache cache)
{
if (cache == null)
throw new ArgumentNullException("cache");
DataArray frame = cache.CacheData;
if (frame == null)
throw new ArgumentNullException("cache.CacheData");
// do stuff
}
Working version:
public bool CaptureFrame(ArrayCache cache)
{
if (cache == null)
throw new ArgumentNullException("cache");
if (cache.CacheData == null)
throw new ArgumentNullException("cache.CacheData");
DataArray frame = cache.CacheData;
// do stuff
}
The problem is this: frame is not null (at least according to the debugger, and by any measure I can trace of the code), however when it does the if (frame == null) check, it comes out true and throws the exception. I rewrote to check cache.CacheData and it works fine, but it really shouldn't make any difference to the code logic.
I managed to find one other question on the site with a similar problem, which ended up being related to the == and != operators being overloaded. Those operators are not overloaded for the class in question in my code, and it's a standalone class so there's nothing for it to inherit.
Edit: John Saunders requested code for the CacheData property:
private DataArray cacheData;
public DataArray CacheData
{
get
{
return cacheData;
}
set
{
cacheData = value;
}
}
looks like you are mapping the exception in the non working one then calling
DataArray frame = cache.CacheData;
but what if cache.CacheData if null then you are assigning it to DataFrame.. it's always best in my opinion to do the Check for null first before assigning or assuming your second one looks fine.. prehaps instead of throwing an exception maybe you could trap the exception and try some test cases for both scenarios
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.