DateTime mydt = new DateTime();
mydt = Convert.ToDateTime(com.Decrypt(Request.QueryString["Time"].ToString(), com.KeyCode.ToString()));
What am I doing wrong ? Its giving NullReferenceException.
Well, it's hard to say exactly what's going on because you've got lots of stuff going on in one statement.
As a simple aid to debugging, break that statement up into several separate ones - it'll make it a lot easier to find out what's going wrong. (Also note that your initial value of mydt is overwritten in the next statement anyway, so there's no point in it.)
Here's how I would rewrite your code:
// This already returns a string... you don't need to call ToString() on it
string encryptedTime = Request.QueryString["Time"];
// We don't know what "com" is here...
string key = com.KeyCode.ToString();
string decryptedTime = com.Decrypt(encryptedTime, key);
DateTime mydt = Convert.ToDateTime(decryptedTime);
(I'd also usually use DateTime.TryParseExact, but that's a different matter.)
A NullReferenceException occurs when you try to access a member of a null reference.
When you have a series of member accesses (using the '.' operator) and any reference is null, this will occur.
Any of these could be null:
com
Request.QueryString["Time"]
com.KeyCode
You can debug this by stopping on this line with a breakpoint (click on the line, press F9), and hover on each item in the above list. One of them is bound to be null.
Here's how you might redo your code in order to make it easier to read and debug issues like these:
DateTime mydt; // You don't need to initialize this with a new DateTime
if (com == null)
{
// Do something else, since nothing below this will work
}
var keyCode = com.KeyCode;
var time = Request.QueryString["Time"];
if (keyCode == null || time == null)
{
// Do something else, since nothing below this will work
}
mydt = Convert.ToDateTime(com.Decrypt(time.ToString(), keyCode.ToString()));
There are many possible null references here, but the most likely one is the Time query string variable. Make sure it exists.
Also, is your com variable set? And the com.KeyCode?
Several things can be null..
com, Request.QueryString["Time"], com.KeyCode
Set a breakpoint and find out ;)
One of your objects is null and when you try to access a property of a object that's null you receive a NullReferenceException.
Break out the code into multiple lines and test as either com, Request.QueryString["Time"] or com.KeyCode is null.
NullReferenceException come when a operation work on a object who have a null value or not have a valid value. you need to check that object have valid value or not null before making a operation on them.
if you parse it from anything that check that it is valid in some case if value not valid then he set the object as null in .net
As its name indicates, NullReferenceException is thrown because you are calling methods or properties on something that is null.
Therefore, you need to debug that expression to see which object is null at runtime, in the page you are testing.
We don't have enough info to answer your question directly. But...
There might not be a "Time" parameter in the query string?
Your variable com might be null? Was it properly instantiated?
As we don't see what page you are calling, we cannot tell.
So fire up visual studio and debug the expressions in there. Anyone of them could be null for any number of reasons.
NullReference essentially means that you are using a reference to an object when that object is null.
Related
while analyzing my code using sonarqube i came across 'variableProducerAgreements' is null on at least one execution path in the following code (the foreach loop):
however, upon looking at it and trying various things, variableProducerAgreements seems to never be null in this foreach loop. during a code review, i'm being told that it can "totally" be null and should add conditional logic to handle it. but i'm not understanding how it can be null and thus not sure how to add a conditional. any ideas?
I can't see a way in which variableProducerAgreements could be null since you have the null guard in place at the top (and assuming you don't have any crazy code in your property getters).
if (userProfile?.ProducerProfile == null)
return result;
The Where and FindAll methods in .NET doesn't return null.
However, it is possible the use of a null-conditional every time you access ProducerProfile is confusing some tools and people. Since you're returning early if it is null, you should remove them:
if (IsActingAsDelegate && userProfile.ProducerProfile.IsInactiveProducer)
{
variableProducerAgreements = userProfile.ProducerProfile.ProducerAgreements.FindAll(ag => ag.IsActive && ag.IsVariableBranchContract);
}
else
{
variableProducerAgreements = userProfile.ProducerProfile.ActiveAgreements.Where(a => a.IsVariableContract);
}
If there was a way for it to be null before the if statement, you would also risk a NullReferenceException when you access the IsInactiveProducer property.
Also, the reviewer should be able to explain his/her reasoning.
I've been searching and reading and trying different things but I can accomplish the most basic thing.
I have a custom object that has several nullable properties.
The problem is that when this property already has data it won't set to null.
The code is simplified for simplicity on this post.
This method takes data passed on to modify a record in a database. So in the line where I create the subscription object I use a paramter to know if it is a new record or I'm modifying an existing.
When I want to modify an existing one, it look in the database for the record and the returns the object populated with the data from the database. Then I overwrite the object properties with the new data and save again.
What it is happening is that if I want to overwrite an existing record that has data on the property FechaAlta, and set this date to null, the object property FechaData won't set to null.
Hope it is clear enough.
public string ProcessSubscription(string cRMID, string suscripID, DateTime? fechaAlta = null)
{
Subscription subscription = null;
....
subscription = new Suscription(modify)
....
subscription.CRMID = cRMID;
subscription.SuscripID = suscripID;
subscription.FechaAlta = fechaAlta;
....
return _update.UpdateEntity(subscription);
}
This is what the debugger is showing after that line. I tried to just set it to null for test purposes
.
Image from the debugger
I found the problem. It was a code problem in the set method of the class property.
I was setting the property only if the value != null. I was really dumb
Thanks to all.
Your question is somewhat lacking. But from what I gather you want to set fechaAlta to null in your function when certain conditions are met? If that is the case, your function isn't even attempting to set fechaAlta to null. All I see is that you have fechaAlta set up as an 'optional parameter', which means that if fechaAlta IS NOT specified when ProcessSubscription() is called, only then it will be null. However, if fechaAlta IS specified when ProcessSubscription() is called, it will never be null because you are not setting it to null.
If you call this, and dateTime is not null, it will never be null:
ProcessSubscription("string1","string2", dateTime);
It will only be null if you call this:
ProcessSubscription("string1","string2");
or
ProcessSubscription("string1","string2", null);
You need to:
subscription.FechaAlta = null;
or...
fechaAlta = null;
...somewhere in your function.
Where is the logic in your function that sets it to null?
When you know id is suppose to exist as in the example below, is it good practice to check for nulls?
var submission = _ctx.Submissions.FirstOrDefault(p => p.Id == id);
submission.Done = true;
_ctx.Submissions.Attach(submission);
_ctx.Entry(submission).State = EntityState.Modified;
_ctx.SaveChanges();
If id is supposed to exist you do not check for null. In fact in this case you should query like this
_ctx.Submissions.Single(p => p.Id == id);
The Single method will throw an exception if the item is not found. On the other hand if you are building a WebAPI or have a specific not found page as the id is sent by the client (i.e. can result by something outside your code) you may use SingleOrDefault, then check for null and return appropriate HTTP status code or redirect to the appropriate page. Basically if null results from not validated data you should check and respond accordingly. If the arguments that cause null values are generated by code you should NOT check for null and in fact query in a way that may not result in null because otherwise you are just covering an error in your code.
This is my opinion which is a result of my personal experience. Note that not everyone agrees as is obvious by the different answers of a question I posted on programmers.stackexchange.com some time ago - https://softwareengineering.stackexchange.com/questions/147480/should-one-check-for-null-if-he-does-not-expect-null
You check for null when you cannot say with complete certainty that the object will never not be null.
With that said, you are using FirstOrDefault(). If it didn't find anything in the criteria, it will return you null.
If you feel that there should always be an object, and that there not being an object in question would mean that there is a bug in the program somewhere, then you should use First not FirstOrDefault. Doing this means that if one of your assumptions for this code ends up being violated you will be informed quickly, loudly, and as close to the source of the problem as possible.
FirstOrDefault should be used if it's entirely sensible for the query in question to have no items, resulting in a null value being returned. If you are in this position, the program should work correctly if the query does in fact return null, or whatever else you need to do for the program to function appropriately.
What you want to avoid is putting yourself in the position where a program (incorrectly) assumes a query always has at least one item, but where you use FirstOrDeafult anyway. Here you end up with NullReferenceExceptions, which can take extra debugging work to figure out where the actual problem is (a query with no items that should have had items).
For resilient code you should definitely check and handle to see if submission is null.
You check for the null values, if there is an error to be occured by passing a null value. You can check them in any way, either by using try catch block or using a an if else block.
You can check it, this way you can prevent the errors that might occur by a null value.
FirstOrDefault documents your intention as "the result I'm expecting may not contain items". In such case you should check for null and perform some reasonable fallback. Throwing exception at that point would look strange.
It sounds like in your case you don't expect empty result, so use First and handle exception somewhere higher on call stack or even let default exception handling to happen.
Suppose I have a method that returns an array or list or some other collection. If something goes wrong inside or when there is simply no data to return, what is better - to return null or to return array (list, etc.) that has length (count) equal to 0?
In fact is it important, or it is just a matter of developer's preferences?
It's better to return an empty collection. This way when someone calls the function like so:
foreach(var i in items)
{
}
it doesn't throw a null reference exception on them.
Technically, you could argue empty vs. null means, but in reality a lot of people (myself included at times) forget to be defensive and don't check to see if the object is null before using it. It's playing into what other people assume is going to happen, which means less bugs and less angry users.
Your iteration code will be a lot easier if you return empty collections instead of null.
However, it may be important to distinguish between an empty collection and no collection of data, so it depends on the semantic of the actual type.
If something "goes wrong" you should throw an exception. If there is no data to return, return an empty collection. Developers generally should not be surprised with a NullReferenceException when they ask for a list of items and there just happen to be none to return.
I could see this going either way. Ultimately an array or collection with have a larger footprint, but is "Safer" in the sense that if the result is being used in future foreach/iterations the result will skip over the code block and not end up with a null object exception.
Well, null and empty have two different meanings. An empty collection effectively means "nothing is here", and could be valid. How would you know if something went wrong based on an empty collection?
While it is safer for the calling method, that doesn't make it better than returning null. Good practice states you should check for null before doing operations on an object. It is cheap anyway.
If something truly went wrong, why cant you throw an exception?
It is developer's preference really.
Returning an empty list
Normally I'd return an empty list so that the receiver of the method's return object doesn't need to check for null and avoid any possible NullReferenceException.
So anyone that expects a list can iterate through the list even though the list is empty (that will be a very quick for-each loop).
Returning null
If you are in an environment where running out of memory is a large issue you could optimize to return null value instead. However that means that everyone that uses the method in question always need to check for null and doesn't solve the problem of possible memory leaks.
If something goes wrong then you shouldn't be returning anything, rather throwing an exception.
You need to agree a consistent approach for the project as to the meaning of NULL and {} and stick to it. Either you are going to use NULL or not, if you are everyone needs to know to check.
I like to think of NULL - not tried to or see if there is anything, there might be some but who knows.
Empty collection - tried to populate and as far as the system is concerned there are no items, which is quite a strong statement.
e.g. Wallet.Notes collection.
NULL - I haven't opened my wallet, so I don't know if I have any notes in it.
List={} - I've checked and I definitely don't have any notes cos I spent it all on beer.
Here is an article by Josh Bloch explaining the same. It's written in Java's context but it should apply to C# equally well.
Return zero-length arrays, not nulls
Although I'd say it's mostly a matter of developer's preference, to return an empty collection might be a better approach.
Let's say you have an object which contains a collection member.
public class Customer {
private IList<Order> _orders;
public Customer() {
_orders = new List<Order>();
}
public IList<Order> Orders {
get {
return _orders;
}
}
}
One generally will prefer to have this member as a readonly property so that its customer's orders don't get lost without any apparent reason. So, returning null is not an option. You would likely work better with an empty collection than a null reference. As such, instantiating the collection within the class constructor is a better approach.
And most importantly, when using DataBinding, for instance, you might get strange behaviour when returning null collection reference, as it will best work with an empty collection instead.
Another example, when iterating through a collection such as:
foreach (Order o in c.Orders) {
// Do something here...
}
This foreach loop will simply not get executed when the collection is empty, without you having to check whether it is a null reference first. It simplifies the code and minimizes its complexity.
This depends on the scenario you're wokring in.
This is the bane of my programming existence. After deploying an application, when this error crops up, no amount of debug dump tells you WHAT object was not instantiated. I have the call stack, that's great, it tells me roughly where the object is, but is there any way to get .NET to tell me the actual name of the object?
If you catch them while debugging, of course the program breaks right on the offending creature, but if it happens after the program is in the wild, good luck.
There has to be a way.
I've explored the exceptions returned in these instances and there is just nothing helpful.
No, it's not possible. The exception happens because a reference is null, and references doesn't have names. Variables and class/struct members have names, but it's not certain that the reference is stored in either of those. The reference could for example be created like this:
someObject.GetInstance().DoSomething();
If the GetInstance method returns null, there is a null reference exception when you try to use the reference to call DoSomething. The reference is just a return value from the method, it's not stored in a variable, so there is nothing to get a name from.
If you have debugging information in the compiled assembly, you will get the line number in the stack trace in the exception, but that is as close as you can get.
NullReferenceException is the most evil of all exceptions in an application. It means a possibly-null reference wasn't checked for a null value before it was accessed.
It's evil, because the runtime can't determine what you were expecting to find in the reference, so it can't tell you what precisely failed to be de-referenced.
The stack trace is your only friend in this exception, where it can at least identify which method threw the exception. If your code is neat enough, it should identify a small amount of code to check through.
Additionally, if you're running with a debug build and have the debugging information with the assemblies, you'll even get source line numbers in the stack trace, so you can know exactly what line the method failed on.
The real answer is to prevent this exception from ever being thrown. It's an indicator that some code was poorly written, failing to deal with the scenario where a reference was null.
If you have a method being called where you need to do something with a reference-type argument that needs to be de-referenced at some point, check for null and throw ArgumentNullException, indicating the name of the parameter:
if(parameter == null)
throw new ArgumentNullException("parameter");
If you are performing an operation within a class and a settable property can be set to null, check before de-referencing it and throw an InvalidOperationException indicating the problem:
if(Property == null)
throw new InvalidOperationException("Property cannot be null.");
You should also make sure that all methods you're calling that can return reference types are guaranteed to return a value. For all those that are not, make similar checks for null and handle the case appropriately.
EDIT:
To clarify, I'm not suggesting you perform a check on every reference-type variable before you de-reference it. That would be madness.
It's about understanding where a variable can be assigned null and where it cannot. If you assign a private field in a class to a non-null value in the constructor, and the value is never assigned again, you don't need to check whether the value is null; the design of your class has made sure it never can be.
A well-designed object will restrict the opportunities for null values being assigned and will use guard code where appropriate to throw exceptions when a null value can be present.
This is one of those instances where you really need to attach to the application and step through the general area of the offending code to figure out where that null reference is coming from.
I think currently the best you can get is the line no.
StackTrace:
at test_003.Form1.button1_Click(Object sender, EventArgs e) in C:\Documents and Settings\...\Projects\test_003\test_003\Form1.cs:line 52
If they do something in future about this problem, it would be great.