So, let me explain my trouble.
I get a project which was develop by another guy, and he leaved the firm. Now i have to update the program but something going wrong when i import the solution.
Let see the code:
ListeDeTypeDePoste = (from e in xml.Descendants("profil")
select new TypeDePoste()
{
Nom = e.Element("name").Value,
Chaines = (from c in e.Elements("Chaine")
select new Chaine()
{
Code = c.Element("Code")?.Value,
Type = c.Element("Type")?.Value,
Nom = c.Element("Nom")?.Value,
OU = c.Element("OU")?.Value
}).ToList()
}).ToList<TypeDePoste>();
The trouble is on the .?Value for each properties in a Chaine Class, when i debug i can even debug the solution and if i remove them i got a NullReferenceException. With this code the previous realese .exe worked like a charm
You can use the operator ?. only in C# 6.0.
This is null-propagation operator. If you don't want to use it, you can change your assignment to properties of Chaine class:
select new Chaine()
{
Code = (c.Element("Code") == null) ? null : c.Element("Code").Value,
Type = (c.Element("Type") == null) ? null : c.Element("Type").Value,
Nom = (c.Element("Nom") == null) ? null : c.Element("Nom").Value,
OU = (c.Element("OU") == null) ? null : c.Element("OU").Value
}).ToList()
If you delete ? in this operator the assignment will crash because you try to get value of null.
If c.Element("Code") is null then this code will simply assign null to Code:
Code = c.Element("Code")?.Value;
But without ?:
Code = c.Element("Code").Value; //app will throw an exception because c.Element("Code") is null
This is because the Element calls in that code are sometimes returning null, because an element with the given name doesn't exist at that location in the XML document you're processing.
The ?. (null-conditional) operator tests for this, returning null in such a scenario.
If you use . instead (without adding your own null check), then a NullReferenceException will be thrown in such a scenario. This is by-design in C#.
The null-conditional operator was introduced in C# 6, so to use it you'll need to install Visual Studio 2015.
Related
I have just installed ReSharper, and it has altered
if(dto != null)
{
return new test{
obj1 = "",
obj2 = "",
}
}
into
return dto?.Select(item => new test
{
return new test{
obj1 = "",
obj2 = "",
}
I have not seen before
dto?.Select
tried to google the meaning with no luck.. could someone please explain , or point me in the right direction to the deffination
I gather its simply checking for null?
Null propagation operator is newly introduced in C# 6. return dto?.Select... means, if dto is null then this statement will return null else will execute the remaining part.
Another example, just making it up, assume you have Employee object with Address property which inturn has Lane (string), Pincode etc.
So if you need to get the address lane value you could do:
var lane = employee?.Address?.Lane;
Which will return null if employee or address is null; otherwise returns lane value.
This could be combined in many ways and is really handy.
For eg,
int someIntegerValue = someObject?.SomeIntValue ?? 0;
Basically you could avoid many null checks with this feature.
The question-mark operator acts on nullable values and
x?<operation>
translates to
x.HasValue ? x.Value.<operation> : null
It's basically saying "do this if I'm not null; otherwise keep me as null".
Do you have a
return null
statement later in your original code? I am surprised ReSharper would assume a return null in its transformation.
If you check an object for its type and find out it is of the type you checked for, and you convert it to this type, can this type still be null after conversion ?
The code quality scanning app I'm running is complaining about the following:
if (tx.Tag is ExtendedNodeInfo && ty.Tag is ExtendedNodeInfo)
{
var tagX = tx.Tag as ExtendedNodeInfo;
var tagY = ty.Tag as ExtendedNodeInfo;
// HP Fortify scan says the below line's use of tagX/Y can be null.
// If I add null checks below for taX/Y, Resharper says
// its redundant as its always not null
return tagX.Ordinal.CompareTo(tagY.Ordinal);
}
If tx.Tag doesn't change its value, that's fine - but presumably the code quality scanner doesn't know that. It's generally better to use as for this, so that you only evaluate the property once, only perform the type test once, and then just check the references:
var tagX = tx.Tag as ExtendedNodeInfo;
var tagY = ty.Tag as ExtendedNodeInfo;
if (tagX != null && tagY != null)
{
return tagX.Ordinal.CompareTo(tagY.Ordinal);
}
if (tx.Tag is ExtendedNodeInfo && ty.Tag is ExtendedNodeInfo)
After this line, you have the following guarantees:
tx and ty are not null (otherwise, a NullReferenceException would have been thrown)
both tx.Tag and ty.Tag are of type ExtendedNodeInfo, so you can safely cast them to that type, so in your example both tagX and tagY are guarantueed to be not null
If the warning is about the use of txTag or tyTag, then this is wrong, IMO. But possibly, the warning is about the unchecked dereferencing of Ordinal?
I'm using C# to write a simple program to read Active Directory and display the value held in a AD field on a Windows form program.
If a property doesn't exist then the program crashes, below is my code, how can I catch this and move on to the next field without doing a try/catch for each and every attribute?
DirectoryEntry usr = new DirectoryEntry("LDAP://" + domain, username, password);
DirectorySearcher searcher = new DirectorySearcher(usr);
searcher.Filter = "(sAMAccountName=" + GlobalClass.strUserName + ")";
searcher.CacheResults = false;
searcher.SearchScope = SearchScope.Subtree;
searcher.PropertiesToLoad.Add("givenName");
searcher.PropertiesToLoad.Add("telephoneNumber");
//program crashes here if telephoneNumber attribute doesn't exist.
textBoxFirstName.Text = usr.Properties["telephoneNumber"].Value.ToString();
Just checking usr.Properties["telephoneNumber"] will not work. You must check the actual value. The reason the error is occuring is because you're calling ToString() on Value which is null.
user.Properties will always return a PropertyValueCollection, regardless of the property name entered into the collections indexer.
I.e.
var pony = usr.Properties["OMG_PONIES"]; // Will return a PropertyValueCollection
var value = pony.Value; // Will return null and not error
You need to check the value itself, the best way through the null coalescing operator:
textBoxFirstName.Text = (usr.Properties["telephoneNumber"].Value
?? "Not found").ToString();
Store the contents of usr.Properties["telephoneNumber"]; in a variable and check for null:
PropertyValueCollection tel = usr.Properties["telephoneNumber"];
textBoxFirstName.Text = (tel != null && tel.Value != null)
? tel.Value.ToString()
: "";
Use the null-coalescing operator (??) operator.
textBoxFirstName.Text = (usr.Properties["telephoneNumber"].Value
?? String.Empty).ToString();
This way the value is replaced with an empty string if null. You could also just return null instead of String.Empty, the reason your code is crashing is because you're trying to call ToString() on a null value.
Something like this should work. If telephoneNumber is not null, it will convert the value to a string, otherwise it will use an empty string.
textBoxFirstName.Text = usr.Properties["telephoneNumber"].Value != null
? usr.Properties["telephoneNumber"].Value.ToString()
: "";
A couple of things will help this be more graceful:
Test usr.Properties["telephoneNumber"] for null before calling child properties like Value. I haven't worked with AD myself, but most string-keyed indexers are designed to gracefully handle non-existent keys. the CLR, on the other hand, will happily throw a NullReferenceException any time you try to reference a member of anything that evaluates to null.
On the off chance that AD DOES blow up on a nonexistent column, enclose the assignment in a Try-Catch block that will show an error on the screen and gracefully continue processing (or not).
Use this code
SearchResult.Properties.Contains("property")
To check if the object actually has the prop loaded from the search result
if (usr.Properties["telephoneNumber"] != null)
textBoxFirstName.Text = usr.Properties["telephoneNumber"].Value.ToString();
I have the following line of code:
var selectedDomainID = lkuDomainType.EditValue.Equals(null)
? string.Empty
: lkuDomainType.EditValue;
Sometimes this generates a NullReferenceException. What I don't understand is why. Isn't the whole point of my code to check for null and if so assign string.empty? When I check in DEBUG it is stating that EditValue == null so what am I missing?
Use lkuDomainType.EditValue == null, otherwise you are trying to call an instance method on a null object. But the better option might be lkuDomainType.EditValue ?? String.Empty. Also watch out for lkuDomainType being null, unless it is a class not an object.
When you use Object.Property and Object is undefined, you are dereferencing a null pointer and that's why you get the exception. Instead, use:
var selectedDomainID = lkuDomainType.EditValue == null ? string.Empty : lkuDomainType.EditValue;
If EditValue is null then you can't call Equals. In this cas you would have to do:
var selectedDomainID = lkuDomainType.EditValue == null ? string.Empty : lkuDomainType.EditValue;
Or you can simplify it by doing:
var selectedDomainID = lkuDomainType.EditValue ?? string.Empty;
you are trying to call the Equals method on a null object - do it like this instead:
lkuDomainType.EditValue == null
The problem is that you are using the object before checking if it's null. You are calling the Equals method of the object, which fails if the reference is null.
You have to exchange your lkuDomainType.EditValue.Equals(null) for lkuDomainType.EditValue == null.
EditValue == null. That means that there is no object there. You cannot call functions on null objects, even if the function is .Equals().
You're better off just saying "(lkuDomainType.EditValue == null)" in this case.
You should use String.IsNullOrEmpty here. Like this:
var selectedDomainID = String.IsNullOrEmpty(lkuDomainType.EditValue) ? string.Empty : lkuDomainType.EditValue;
Equals is a method, you're trying to call a method on a null object which is throwing an exception.
when EditValue is null you cannot call the Equals method on it so the best way to check is to use
lkuDomainType.EditValue == null ? string.Empty : lkuDomainType.EditValue;
If lkuDomainType.EditValue is null, then "lkuDomainType.EditValue.Equals(someObject)" is the same as coding "null.Equals(someObject)". Well, obviously "null" doesn't have any members or methods (it wouldn't be null if it did). That's why you get a NullReferenceException.
Most of the examples from the other posts will work, including String.IsNullOrEmpty, which is a method that returns a boolean value.
All current answers fail to address a critical point: the difference between calling Equals on a Nullable type (which is a struct) vs. class type.
Calling Equals on a Nullable typed object whose value is null will not issue an exception, while doing the same on a class typed object will.
Consider the following code:
int? num = null; // int? is Nullable<int>
String s = null; // String is a class
var equalsNullable = num.Equals(null); // works
var equalsClass = s.Equals(null); // throws
The reason is that Nullable's HasValue method is called in such case, see Jon Skeet's answer for more info.
As other people said, the way to go in the OP's case is to use == or ??.
I have the following LINQ query which always results in an error when my "Remark" column in dtblDetail is null, even though I test if it is NULL.
var varActiveAndUsedElementsWithDetails =
from e in dtblElements
join d in dtblDetails on e.PK equals d.FK into set
from d in set.DefaultIfEmpty()
where (e.ElementActive == true)
select new
{
ElementPK = e.PK,
Remark = d.IsRemarkNull() ? null : d.Remark
};
The error message was:
"The value for column 'Remark' in table 'dtblDetails' is DBNull."
After adding the test for d.IsRemarkNull() a null reference exception is thrown.
Can you help me with this?
I've already checked the following websites but didn't find anything useful other than that I have to test for DBNULL. But as said this doesn't solve my problem.
http://social.msdn.microsoft.com/Forums/en-US/linqprojectgeneral/thread/3d124f45-62ec-4006-a5b1-ddbb578c4e4d
http://blogs.msdn.com/adonet/archive/2007/02/13/nulls-linq-to-datasets-part-3.aspx
http://www.vbforums.com/showthread.php?t=506645
The problem was that the whole 'd' item was empty.
So calling 'd.IsRemarkNull()' resulted in the null reference exception.
The following code fixed the problem:
var varActiveAndUsedElementsWithDetails =
from e in dtblElements
join d in dtblDetails on e.PK equals d.FK into set
from d in set.DefaultIfEmpty()
where (e.ElementActive == true)
select new
{
ElementPK = e.PK,
Remark = d == null? null : (d.IsRemarkNull() ? null : d.Remark)
};
Where is the error coming from? Is it possible that it is the d.IsRemarkNull() that is causing it? What does that method look like?
Perhaps:
DBNull.Value.Equals(d.Remark)
maybe this field doesn't allow null in db, get a default value for it, and avoid handling null values