A safe way to get some deep value [duplicate] - c#

This question already has answers here:
Elegant way to avoid NullReferenceException in C#
(4 answers)
Closed 3 years ago.
Suppose I have a fairly deep class, and I need to get some field embedded deep within
int? result = this.child.button.data;
return result;
And at any point, it could be pointing to a null, in which case I want to return null as well. A common approach would be
if (this.child != null && this.child.button!= null) {
return this.child.button.data;
} else {
return null;
}
But if the field is REALLY deep nested, then the only solution I can think of is this:
int? result = null;
try {
result = this.child.button.handler.controller.renderer.data;
} catch (NullReferenceException ex) {
// Do nothing here
}
Is this the correct approach, or is there a better solution?

you may check the null conditional operator in C# - ?.
Like:
result = this?.child?.button?.handler?.controller?.renderer?.data;

Related

C# Cognex ,why he say null reference exception [duplicate]

This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 4 years ago.
enter image description here
code:
CogFindCircleLastRunRecordConstants.BestFitCircle;
CogFindCircleTool_.Run();
if ((CogFindCircleTool_.Results.GetCircle() != null) && (CogFindCircleTool_.Results.GetCircle().Visible == true))
{
cogRecordDisplay1.Record = CogFindCircleTool_.CreateLastRunRecord().SubRecords["InputImage"];
This error is because .Results is null, yet you're trying to call the GetCircle() method on it.
One way to handle this is to use the null-conditional operator (?.), which returns null if the left hand side is null, otherwise continues with the method or property on the right hand side:
// If Results is null, the call to GetCircle will not happen, and the result will be null
// Not needed on the second condition, since '&&' would return 'false' right away
if ((CogFindCircleTool_.Results?.GetCircle() != null) &&
(CogFindCircleTool_.Results.GetCircle().Visible == true))
You could shorten your code even further by adding another .? when accessing the Visible property, and then we don't need to explicitly check for .GetCircle() != null first.
Below, if Results is null or GetCircle returns null, the expression will fail (because null != true), otherwise the condition Visible == true will be evaluated:
if (CogFindCircleTool_.Results?.GetCircle()?.Visible == true)
In the comments you stated that you have a line like this inside the if statement:
Label.SetXYText(CogFindCircleTool_.Results.GetCircle().CenterX,
CogFindCircleTool_.Results.GetCircle().CenterY, "(" +
Math.Round(CogFindCircleTool_.Results.GetCircle().CenterX, 3).ToString() +
"," + Math.Round(CogFindCircleTool_.Results.GetCircle().CenterY, 3).ToString() + ")");
One thing to improve performance is to capture the result fo the GetCircle() method once rather than calling it over and over again, which takes extra processing cycles. This will also make the code shorter and more readable. You can also use string interpolation instead of concatenation to shorten the code a little more.
You also mentioned that you were still getting a null reference exception on the inner line, which could only mean that Label is null (from what I can tell). If so, we could use the ?. operator when calling the SetXYText method:
// Capture the result of GetCircle() once
var circle = CogFindCircleTool_?.Results?.GetCircle();
if (circle?.Visible == true)
{
Label?.SetXYText(circle.CenterX, circle.CenterY,
$"({Math.Round(circle.CenterX, 3)},{Math.Round(circle.CenterY, 3)})");
}
Note that the code above will not do anything if something is null. If you want to do something else if circle is null or Label is null, then you should explicitly check that rather than use the ?. operator:
if (circle == null)
{
// do something if circle is null
}
else if (circle.Visible == true)
{
if (Label == null)
{
// do something if Label is null
}
else
{
Label.SetXYText(circle.CenterX, circle.CenterY,
$"({Math.Round(circle.CenterX, 3)},{Math.Round(circle.CenterY, 3)})");
}
}

Null string exception [duplicate]

This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 6 years ago.
Before i ask my question i need to mention that i looked up in the site to solve the problem but i didnt find nothing.
Here is my function :
public string GetAccessToken(int agencyId)
{
string retrunString = null;
Token fbToken = tokenMgr.Get(agencyId, "FacebookInsights");
if (String.IsNullOrWhiteSpace(fbToken.AccessToken)) **
return retrunString;
else
return fbToken.AccessToken;
}
When Token is an object which include a String field name : AccessToken.
When i debug the code and reach the line with the ' ** ' when fbToken.AccessToken is NULL , I get an exception " Object reference not set to an instance of an object."
When i looked up in other threads they suggest to use String.IsNullOrWhiteSpace , but it didnt solve the problem and i keep getting the error.
I would greatly appreciate any help , thanks in advance!
fbToken is null, not fbToken.AccessToken. Use something like this:
if ( fbToken == null || String.IsNullOrWhiteSpace(fbToken.AccessToken) )
New C# 6.0 allows you to do null propagation to accomplish this as well:
if ( String.IsNullOrWhiteSpace(fbToken?.AccessToken) )
Write it like this. Check Null-conditional Operators
if(String.IsNullOrWhiteSpace(fbToken?.AccessToken))
{
//your stuff
}
You have to validate the object fbToken and not his member AccessToken.
public string GetAccessToken(int agencyId)
{
var fbToken = tokenMgr.Get(agencyId, "FacebookInsights");
return (fbToken == null) ? null : fbToken.AccessToken;
}

Reflection based comparion of two object values [duplicate]

This question already has an answer here:
Comparing two objects by iterating recursively through all the properties' properties?
(1 answer)
Closed 7 years ago.
Are there any libraries/frameworks for .net that would take two objects of the same type and using reflection match values of all the properties?
I had to compare two objects having 2 Nullable DateTime properties and the code lookes ugly as hell:
private bool SameValues(ExpiryDates ExpiryDates1, ExpiryDates ExpiryDates2)
{
//Assume they are the same value and then look for differences
bool result = true;
if (ExpiryDates1.PSL_ExpiryDate.HasValue != ExpiryDates2.PSL_ExpiryDate.HasValue)
{
result = false;
}
if (ExpiryDates1.MNL_ExpiryDate.HasValue != ExpiryDates2.MNL_ExpiryDate.HasValue)
{
result = false;
}
if ((ExpiryDates1.MNL_ExpiryDate != null) && (ExpiryDates2.MNL_ExpiryDate != null))
if (ExpiryDates1.MNL_ExpiryDate.Value != ExpiryDates2.MNL_ExpiryDate.Value)
result = false;
if ((ExpiryDates1.PSL_ExpiryDate != null) && (ExpiryDates2.PSL_ExpiryDate != null))
if (ExpiryDates1.PSL_ExpiryDate.Value != ExpiryDates2.PSL_ExpiryDate.Value)
result = false;
return result;
}
There is no library avaiable as per my knowldege but in .NEt framework for comparison of same type of object we have IComparare interface that you can use and do comparison between two object of same type.
public class BoxComp : IComparer<Box>
{
// Compares by Height, Length, and Width.
public int Compare(Box x, Box y)
{
///you code to do comparison
}
}
you can aslo make it generic.
You can check this : Compare .NET Objects but i suggest to go for comparare impmentation as there is no big need as you just want to compare datetime of two object.

Clean way to catch error Object reference not set [duplicate]

This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 7 years ago.
When DeliveryMethodComboBox has no selectedItem, the
Object reference not set to an instance of an object.
error appears.
what is the best way to solve this?
In this example i've added a try and catch.
try
{
DeliveryMethodLabel2.Text = DeliveryMethodComboBox.SelectedItem.ToString();
}
catch
{
DeliveryMethodLabel2.Text = "";
}
I'm assuming you mean that the value is null
** Assumes you don't have nulls in your list and that you are only concerned about whether there is a selection or not.
if(DeliveryMethodComboBox.SelectedIndex != -1)
{
DeliveryMethodLabel2.Text = DeliveryMethodComboBox.SelectedItem.ToString();
}
else
{
DeliveryMethodLabel2.Text = "";
}
Otherwise, if DeliverMethodComboBox can be null, just change the if to
if(DeliveryMethodComboBox != null && DeliveryMethodComboBox.SelectedIndex != -1)

C#: reducing line noise in sanity checks [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Shortcut for “null if object is null, or object.member if object is not null”
I wish there were a way to make this type of test simpler in C#:
if (foo != null &&
foo.bar != null &&
foo.bar.baz != null &&
foo.bar.baz.bat != null)
{
var bat = foo.bar.baz.bat;
bat.cat = 5;
bat.dog = 6;
}
One possible feature that would support this is if statements that supported new variable declarations, e.g.
if (foo != null &&
(var bar = foo.bar) != null &&
(var baz = bar.baz) != null &&
(var bat = baz.bat) != null)
{
bat.cat = 5;
bat.dog = 6;
}
The gains may not be obvious here, since the proposed solution is actually longer in this example. But with longer names it would really pay off.
Is there any better way to do this? Any chance of a suggestion like this actually making it into a future version of the language (calling Eric Lippert, come in)?
This is a fairly frequently requested feature, and as a result this question has now been asked several times on StackOverflow. See
Shortcut for "null if object is null, or object.member if object is not null"
for some thoughts on it.
Good question, but bad intentions. Your code is going to ignore the Law of Demeter
I usually just move the expression in the if-statement to its own method at the bottom of the file:
if (CheckBat(foo))
{
var bat = foo.bar.baz.bat;
bat.cat = 5;
bat.dog = 6;
}
... snip ...
private bool CheckBat(MyFoo foo)
{
return foo != null &&
foo.bar != null &&
foo.bar.baz != null &&
foo.bar.baz.bat != null;
}

Categories

Resources