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.
Related
Short Version
How to make the C# nullable type checking compiler realize that the variable customer cannot be null after the call returns:
Constraints.NotNull(customer);
.NET Fiddle: https://dotnetfiddle.net/ZcgRCV
Long Version
If i have code like:
#nullable enable
Customer? c;
...
Console.WriteLine(customer.FirstName);
The compiler will (correctly) warn me that customer might be null when i try to access .FirstName:
customer.FirstName ⇐ possible null dereference
Guard Constraint
I want to perform a guard, or a constraint that will tell the C# 8 nullable type checker that the value cannot be null. I'll call a function that guarantess that the variable cannot be null after the function returns:
#nullable enable
Customer? customer;
...
Constraint.NotNull(customer, "Customer"); //if this function returns customer is definitely not null
Console.WriteLine(customer.FirstName);
Where Constraint.NotNull is something like:
public static class Constraint
{
public static void NotNull(Object? o, String msg="")
{
if (o == null)
throw new Exception("Object cannot be null "+msg);
}
}
And the guard does its job; it raises an exception. But the compiler doesn't realize that customer cannot be null after Constrant.NotNull returns:
Another Example
A better example, i came across in some old code:
Customer? currentCustomer;
//...
EnsureCurrentCustomer();
DoSomethingWithIt(currentCustomer); // guaranteed not null because EnsureCurrentCustomer did it,
// but the compiler doesn't know that.
We need a way for EnsureCurrentCustomer to tell the C# 8 nullable type checker that the variable currentCustomer cannot be null after EnsureCurrentCustomer function returns.
How do?
Attempt 1: Null forgiving (!) operator
No. I want to work with the type system, not hide the land-mines (as Microsoft reminds you)
Attempt 2: https://stackoverflow.com/a/58282043/12597 (gives its own error)
Attempt 3: https://stackoverflow.com/a/65076221/12597 (No, see #1)
ChatGPT says the only way to do it is to use the JetBrains [NotNull] constraint; which i don't have access to.
If you just change the call site ever so slightly:
customer = Constraint.NotNull(customer, "Customer");
Then you can just do:
public static class Constraint {
public static T NotNull<T>(T? t, string? msg="") where T: notnull {
if (t is null) {
throw new Exception("Object cannot be null "+msg);
}
return t;
}
}
For the second example, assuming currentCustomer is a field, you can use MemberNotNull:
[MemberNotNull("currentCustomer")]
void EnsureCurrentCustomer() {
if (currentCustomer is null) {
throw new Exception(...);
}
}
If currentCustomer is instead a local variable and EnsureCurrentCustomer is actually a local function, then I would do something similar to Constraint.NotNull, i.e. changing the caller to:
currentCustomer = EnsureCurrentCustomer()
and just use a non nullable Customer for the return type.
This is achieved using the [NotNull] annotation on the argument being verified in your guard-clause method. A good reference for this is in the ArgumentNullException.ThrowIfNull static method. The summary of the NotNullAttribute says:
Specifies that an output will not be null even if the corresponding type allows it. Specifies that an input argument was not null when the call returns.
You can also refer to xUnit's Assert.NotNull assertion, which does the same thing.
I have an object where a property may exist or may not exist.
if(response.AddressInformation.AddressResponses.Any(inf => inf.AddressResponse.matchCodeStatus.ToLower().Equals("usps_match")))
{
}
I have two array items of AddressResponse. First item has null for matchCodeStatus and thats where I get object not set to an instance exception. How can I achieve my target and escape this exception?
I tried to put a null check before my IF, but it didnt work
if(response.AddressInformation.AddressResponses.Any(inf => inf.AddressResponse.matchCodeStatus != null)
As of C# 6, you can also use a null conditional operator ?. :
inf => inf.AddressResponse.matchCodeStatus?.ToLower().Equals("usps_match"))
I would like to know if there is a better way or general rule to check null result before accessing property or calling method in C# Linq or lambda expressions. Thanks in advance.
At my understanding, to avoid exception like "Object reference not set to an instance of an object" or "Check null from Lambda result before accessing CSharp property or calling method", I should use "if" statement, or "try/catch" block like:
var product1 = _myProductRepository.FindOne(p => p.Id == -20301);
//1. use "if" statement to let code flow continue
if(product1 != null) // to prevent exception "Object reference not set to an instance of an object."
{
int id1 = sh1.Id; // note: accessing property "Id" is safe here
Console.WriteLine("Product Id: {0}", id1);
}
//2. use "try/catch" block to let code flow continue
var product2 = _myProductRepository.FindOne(123);
var possibleItems = product2.Orders.Where(x => x.Id == -1);
List<Order> myOrderList = null;
try
{
myOrderList = possibleItems.ToList(); // note: ToList() method call is safe here
}
catch
{
myOrderList = new List<Order>();
}
I should use "if" statement, or "try/catch" block like:
In general, I would prefer an explicit null check if the null return is something that is expected as part of the normal operation of your application.
In your case, this is likely true, as finding a product seems like an operation that very well could fail, as a product may not exist.
That being said, if the ID is a known element and really should always be in the DB, then null would not be an expected result. In this case, the FindOne method really shouldn't return a null instance, and that is truly an exceptional case, then exception handling may be preferred.
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.
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();
}