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

I have been using the code,
object amountObject = MySqlDAL.ExecuteQuerySingle(query);
if (amountObject.Equals(System.DBNull.Value))
{
return amount;
}
here in some point am getting an exception "Object reference not set to an instance of an object." from the sentence amountObject.Equals(System.DBNull.Value). Its working fine for some set of data.
What may be the reason? Can any one please help me out?

Try checking the result for null as well..
if (amountObject ==null || amountObject.Equals(System.DBNull.Value))
{
return amount;
}

Presumably MySqlDAL.ExecuteQuerySingle is returning null instead of System.DBNull.Value. It's hard to know whether that's a bug in your expectations or in ExecuteQuerySingle though.

Sometimes the query doesn't return a value, therefore amountObject is null.
Manually run the query with the parameters that make this fail, there's something wrong with your SQL.

Just change:
if (amountObject.Equals(System.DBNull.Value))
{
return amount;
}
to:
if (amountObject != null && amountObject.Equals(System.DBNull.Value))
{
return amount;
}

Have you checked if amountObject is null? It seems that the returned value by MySqlDAL.ExecuteQuerySingle return NULL.

Related

IList<> Property stays null even when member is instantiated

I am having trouble using an IList property which always seems to return null, even though the member is is getting is instantiated:
private List<ModelRootEntity> _validTargets = new List<ModelRootEntity>();
public IList<IModelRootEntity> ValidTargets
{
get
{
return _validTargets as IList<IModelRootEntity>;
}
protected internal set
{
if (value == null)
_validTargets.Clear();
else
_validTargets = value as List<ModelRootEntity>;
}
}
ModelRootEntity implements IModelRootEntity. I watched both values during debugging, whilst the member shows a positive count, the property stays null.
I also tried raising an exception within the property getter to throw if the counts of _validTargets and _validTargets as List<ModelRootEntity> are different, but it never threw.
Found question [Dictionary properties are always null despite dictionaries being instantiated, which seems similar, however in my case this seems to happen regardless of serialization.
Any ideas?
If you set your property to any value that isn't a List<ModelRootEntity>, the as expression will return null and the property will become null.
I found the answer, thanks to #Nilesh comment above.
Replacing:
private List<ModelRootEntity> _validTargets = new List<ModelRootEntity>();
with:
private List<IModelRootEntity> _validTargets = new List<ModelRootEntity>();
exposed the real issue. The second line will not compile. The following post explained why:
C# newbie List<Interface> question
The only odd thing was the exception I tried to force which never threw, and "threw" me off.

How to check if DateTime object was not assigned?

So, First of all. Code:
I've got a class:
public class Myobject
{
public string Code { get; set; }
public DateTime? StartDate { get; set; }
}
And this is part of very simple source:
MyObject mo = new MyObject();
mo.Code= "sth";
// NO action on StartDate property!
if (mo.StartDate.HasValue)
{
sc.Parameters.Add(new SqlParameter("#inStartDate", mo.StartDate.Value));
}
else
{
sc.Parameters.Add(new SqlParameter("#inStartDate", DBNull.Value));
}
Simple 'if' - Sql Server 2008, throw an error - when gets null Datetime (it has to be DBNull.Value)
So I want to check it first, and then pass right value or DBNull.
My problem is - this 'if' always retruns true! Why!?
Also tried that:
if (mo.StartDate.Value == null)
but it always returns false. How come it is not a null? It was not even created..
So.. How to check if DateTime object was not assigned?
Try this:
if (mo.StartDate.GetValueOrDefault() != DateTime.MinValue)
{
// True - mo.StartDate has value
}
else
{
// False - mo.StartDate doesn't have value
}
should just be able to do
mo.StartDate != null
instead of
mo.StartDate.Value != null
Running the simplest test with that class (as you presented it) yields false:
var mo = new Myobject();
Console.WriteLine(mo.StartDate.HasValue);
Output is False.
I'd put a breakpoint on your constructor (if you have one), make sure nothing else is getting assigned, and walk through any methods called along the way to make sure there's nothing else setting the property that may not be immediately obvious...
Can you post more code, perhaps? There must be something in code not posted setting the property.
.HasValue and ==null are the ways to check whether DateTime? is assigned a value or not. You are doing it right. There might be problem somewhere else that .HasValue returns true always.
The way you're checking for null is fine, there must be something else that's setting the field's value.
To find what's setting the field you could right-click it then do find all references, then scan the list for any assignments.
Failing that, you could change it to an explicitly defined property temporarily and set a breakpoint within the set method, then execution will pause whenever the value is set and you can look up the call stack.

Object reference not set to an instance of an object

When I try to open the page from my IDE in VS 2008 using "VIEW IN BROWSER" option I get "Object reference not set to an instance of an object" error.
The piece of code I get this error :
XResult = Request.QueryString["res"];
TextBox1.Text = XResult.ToString();
The problem here is that XResult is null and when you call ToString on it the code produces a NullReferenceException. You need to account for this by doing an explicit null check
TextBox1.Text = XResult == null ? String.empty : XResult.ToString();
If you are opening the page without the "res" query string then you need to include a check for null before you do anything with it.
if (Request.QueryString["res"] != null)
{
XResult = Request.QueryString["res"];
TextBox1.Text = XResult.ToString();
}
That error could be Because the REquest.QueryString method did not find a value for "res" in the url so when you try to do the "toString" to a null object whrow that exeption.
Your code is expecting a query string http://localhost:xxxx/yourapp?res=yourval. It's not present in the address supplied to the browser. In the web section of your project properties, you can supply an appropriate URL. Of course, shoring up your code to allow for this would be advisable.
XResult is already a string, so calling ToString isn't necessary. That should also fix your problem.
The problem here is that XResult is null, and when you call ToString
on it the code produces a NullReferenceException. You need to account for this by doing an explicit null check:
if (Request.QueryString["res"] != null)
{
XResult = Request.QueryString["res"];
TextBox1.Text = XResult.ToString();
}

Is this redundant code?

I'm upgrading a system and am going through another developers code (ASP.NET in C#).
I came across this:
private ReferralSearchFilterResults ReferralsMatched
{
get
{
if (Session[SESSION_REFERRAL_SEARCHFILTERRESULTS] == null || Session[SESSION_REFERRAL_SEARCHFILTERRESULTS].GetType() != typeof(ReferralSearchFilterResults))
return null;
else
return (ReferralSearchFilterResults)Session[SESSION_REFERRAL_SEARCHFILTERRESULTS];
}
set
{
if (value == null)
{
Session[SESSION_REFERRAL_SEARCHFILTERRESULTS] = value;
}
else if (value.GetType() == typeof(ReferralSearchFilterResults))
{
Session[SESSION_REFERRAL_SEARCHFILTERRESULTS] = value;
}
}
}
Is checking the type on the setter unnecessary? Surely, if I set the property to something other than a ReferralSearchFilterResults object, the code wouldn't even compile? Am I missing something or am I right to think this can be achieved just by using:
set
{
Session[SESSION_REFERRAL_SEARCHFILTERRESULTS] = value;
}
The original code prevents any subclasses of ReferralSearchFilterResults from being set or get to or from the property. This is because value.GetType() will return the actual Type of the object referenced by value. If that Type is a subclass of ReferralSearchFilterResults, then it will not equals typeof(ReferralSearchFilterResults).
I'm not sure of your context here, so I can't tell you whether that's correct behaviour or not. If it's intended behaviour, it does smell a bit dirty as it will silently ignore any assignments of subclasses. But I can't really judge without more context.
I think you're right - the setter shouldn't compile if provided with something of that cannot be implicitly cast to a ReferralSearchFilterResults.
For the get part, you can use
return Session[SESSION_REFERRAL_SEARCHFILTERRESULTS] as ReferralSearchFilterResults;
This returns the value if it can be casted to ReferralSearchFilterResults, otherwise null.
Jamie you are correct. The Type check on the Setter is unnecessary in this case because value must be a ReferralSearchFilterResults.
One other change you might consider is using the is and as keywords in place of comparing Type objects.
private ReferralSearchFilterResults ReferralsMatched
{
get
{
if (Session[SESSION_REFERRAL_SEARCHFILTERRESULTS] == null || !(Session[SESSION_REFERRAL_SEARCHFILTERRESULTS] is ReferralSearchFilterResults))
return null;
else
return Session[SESSION_REFERRAL_SEARCHFILTERRESULTS] as ReferralSearchFilterResults;
}
set
{
Session[SESSION_REFERRAL_SEARCHFILTERRESULTS] = value;
}
}
Session variables are of type object, so you can store anything inside those. But in this case the setter itself prevents the programmer from assigned an other object type than ReferralSearchFilterResults and derived objects.
So the check, as you pointed out, itself is unneccessary. Additionally it does not let a programmer assign a object that derives from ReferralSearchFilterResults.
But I would use Session.Remove rather than just setting the variable to null, because the session variable would still exists in the http context if only set to null.
So:
set
{
if (value == null)
Session.Remove(SESSION_REFERRAL_SEARCHFILTERRESULTS);
else
Session[SESSION_REFERRAL_SEARCHFILTERRESULTS] = value;
}
I can understand the type check in the get bit, but as you say, in the setter, you can't pass in anything that's not a ReferralSearchFilterResults, as the code would fail at the time of compilation.
(Could be some old habit, the other developer had)

ERROR PROMPT: Object reference not set to an instance of an object

public static string GetCurrentEmployeeName()
{
return db.Employees.SingleOrDefault(
c => c.NTUserName == CurrentUsername()
).Last_First;
}
There's no NULL data.
The default of a reference type is null, so if there is no matching record the SingleOrDefault method returns null.
Well, anything could be null in the above statement and you would get the above error.
db
Employees
c.NTUserName
You will have to debug through your code and find it out for yourself.

Categories

Resources