I have this below script in my Class.
aggrgt.Add(new PlainBrgDataSummaryChartAggrgt
{
label = m.label,
goal = m.goal,
groupCode = m.groupCode,
groupValue1 = m.groupValue1,
graphSwitch = m.graphSwitch,
orderByAsc = m.orderByAsc,
metricID = m.metricID,
scoreWk1 = metricscoreWk1.metricScore1,
});
The condition I want is when metricscoreWk1 is null, scoreWk1 = metricscoreWk1.metricScore1 is eliminated.
This may help you:
scoreWk1 = metricscoreWk1.metricScore1 ==null ? 0 : metricscoreWk1.metricScore1
That is, if the value of metricscoreWk1.metricScore1 is null 0(or else any default value) will be assigned else the original value will be assigned to scoreWk1
You can't put "" for Double, the closest analogue, INHO, is Double.NaN (Not A Number):
// Let's have Double.NaN for unknown/undefined etc. value
scoreWk1 = metricscoreWk1.metricScore1 ?? Double.NaN;
You could either:
Create the PlainBrgDataSummaryChartAggrgt object without setting the scoreWk1 field. If metricscoreWk1 is not null, you then set the field and you then add the object to the list.
If you have a setter for metricScore1, you could add a check wherein you ensure that metricscoreWk1 is not null. If it is, the value is not updated.
The second option would allow you to keep your current initialization structure, but the first is more explicit. Should you opt for the second approach, I'd recommend you document it.
Related
I am trying to check if there is at least one Textbox is not null as shown below but that condition will be true if all Textboxare not null not only one at least
foreach (TextBox cont in GB_Search.Controls.OfType<TextBox>())
{
if (string.IsNullOrEmpty(cont.Text))
{
// at least one control
}
}
You can use Linq for this.
The following will check that at least one should not be null and will return true if at least one text box contains value in it:
var oneHasValue = GB_Search.Controls.OfType<TextBox>()
.Any(x=>!string.IsNullOrEmpty(x.Text));
and the following would return true if all are not null or empty:
var allContainValue = GB_Search.Controls.OfType<TextBox>()
.All(x=>!string.IsNullOrEmpty(x.Text));
System.Windows.Controls TextBox
The default value of the TextBox.Text property is an empty string, so unless you've explicitly set it as null I don't see why you'd want to check for nullity.
You're most likely looking to see if any of the TextBox.Text is empty like this:
var result = GB_Search.Controls.OfType<TextBox>()
.Any(textBox => textBox.Text.Length == 0);
or if there is any non-empty:
var result = GB_Search.Controls.OfType<TextBox>()
.Any(textBox => !(textBox.Text.Length == 0));
Note - I've specifically used the Length property of the TextBox to check if it's empty as opposed to String.IsNullOrEmpty, this is simply because as mentioned above TextBox.Text is by default an empty string and as you've mentioned in the comments section under your post you're not explicitly setting it to null, thus there's no need to use String.IsNullOrEmpty as it performs a redundant check that you don't need.
System.Windows.Forms TextBox
Looking to see if any of the TextBox.Text is null or empty:
var result = GB_Search.Controls.OfType<TextBox>()
.Any(textBox => string.IsNullOrEmpty(textBox.Text));
or if there is any non null and non empty:
var result = GB_Search.Controls.OfType<TextBox>()
.Any(textBox => !string.IsNullOrEmpty(textBox.Text));
I have found this example to set the value of a Class property:
Ship ship = new Ship();
string value = "5.5";
var property = ship.GetType().GetProperty("Latitude");
var convertedValue = property.Converter.ConvertFrom(value);
property.SetValue(self, convertedValue);
But I want to set value of a variable in my "this".
i.e. in my main form I have a private double "Momentum"
string value = "5.5";
var property = this.GetType().GetProperty("Momentum");
var convertedValue = property.Converter.ConvertFrom(value);
property.SetValue(self, convertedValue);
This does NOT work - "property" is null.
How do I alter the above code to achieve this?
Seriously, why are you using reflection if you need to set the field value from a variable you own?
Okay, let's forget that... If you have a field and not a property, you need to use GetField:
var value = "5.5";
var field = this.GetType().GetField(nameof(Momentum), BindingFlags.NonPublic);
field.SetValue(self /* or this */, value);
Also, this might be a good place to use nameof, but that is just a suggestion.
I am instantiating an Associate object and assigning properties to it from txtboxes inside of my main form. What is the best practice for null checking? Is it to check each and every property with an if statement before I assign it or is there something a bit better? Here is my code:
Associate updateAssociate = new Associate();
updateAssociate.AssocID = txtAssocId.Text;
updateAssociate.FirstName = txtFname.Text;
updateAssociate.LastName = txtLname.Text;
updateAssociate.HireDate = Convert.ToDateTime(txtHireDate.Text);
updateAssociate.ContractEndDate = Convert.ToDateTime(txtContractEnd.Text);
updateAssociate.TerminationDate = Convert.ToDateTime(txtTerminationDate.Text);
updateAssociate.FullPartTimeID = cboFullPart.SelectedText;
updateAssociate.PrimaryRole = cboPRole.SelectedText;
Based on your comment to the question:
If it is a text box then it would be the .Text property I would want to check for null or blank values before I assign them to the object
You can use the null coalescing operator to check for null values when assigning like that:
updateAssociate.AssocID = txtAssocId.Text ?? string.Empty;
or:
updateAssociate.AssocID = txtAssocId.Text ?? someDefaultValue;
That way if txtAssocId.Text is null then you would assign your defined default to the object property instead of null.
Though I'm not entirely sure a TextBox's .Text property would ever be null instead of an empty string. Maybe you want to check for both?:
updateAssociate.AssocID = string.IsNullOrEmpty(txtAssocId.Text) ? someDefaultValue : txtAssocId.Text;
In C# 6 it would be null-conditional operator.
updateAssociate.AssocID = txtAssocId?.Text;
In prior versions of c# you can write a method to eliminate code duplication. Something like this:
public static T CheckNull<T>(Func<T> canBeNull) where T : class
{
try
{
return canBeNull();
}
catch (NullReferenceException)
{
return default(T);
}
}
And use it like this
updateAssociate.AssocID = CheckNull(() => txtAssocId.Text);
Then you can wrap any code that can throw a null reference into lambda, pass it to this method and no longer bother with it.
I have the following code:
// TryGetAttributeValue returns string value or null if attribute not found
var attribute = element.TryGetAttributeValue("bgimage");
// Convert attribute to int if not null
if (attribute != null) BgImage = convert.ToInt32(attribute);
The thing I don't like is that I have to create a temp variable, attribute, in order to test if it's null or not, and then assign the value to the BgImage variable, which is a nullable int.
I was hoping I could figure out a way to write it all on one line, but I cannot figure a way. I even tried using a ternary statement, but got nowhere:
if (element.TryGetAttributeValue("bgimage") != null) ? BgImage = //Convert result to int : else null;
Realistically, my original two lines of code do the job. I was just hoping to pare it down to one line. But, if anyone knows how to do what I'm trying to accomplish, I'd love to learn how.
I recommend you to use Linq to Xml for parsing Xml (according to your attempt you have BgImage as nullable integer):
BgImage = (int?)element.Attribute("bgimage");
You also can assign some default value if BgImage is not nullable:
BgImage = (int?)element.Attribute("bgimage") ?? 0;
Assuming TryGetAttributeValue returns a string you could do something like
BgImage = convert.ToInt32(element.TryGetAttributeValue("bgimage") ?? "-1")
This would set BgImage to a default value (-1) if the attribute does not exist. If you would prefer to have BgImage set to null when there is no bgimage attribute then it gets a little bit clunkier
BgImage = element.TryGetAttributeValue("bgimage") != null ?
convert.ToInt32(element.TryGetAttributeValue("bgimage")) : (int?)null;
I have a custom class Diary, which has a nullable property DeadlineType
On one of my Forms I have a ComboBox in DropDownList mode, which is populated with all the possible values that DeadlineType can take. When a Diary is selected, the form is populated with all the properties, but I have an issue with the DeadlineType property in that, when it is null, it requires more code than I believe it should i.e.
if (amendDiary.DeadlineType != null)
{
cboDeadlineType.Text = amendDiary.DeadlineType.ToString();
}
else
{
cboDeadlineType.Text = null;
}
I am sure there must be a more concise way to achieve this, or certainly hope so, because this scenario is repeated a lot throughout my application i.e. posting nulls to ComboBoxes.
I did try
cboDeadlineType.Text = amendDiary.DeadlineType.ToString() ?? null
But that gives an 'Object not set to an instance' error.
Try this:
cboDeadlineType.Text = (amendDiary.DeadlineType ?? "").ToString();
Note that setting the ComboBox.Text to null means the same as setting it to "" (The combo Text is empty in both cases).
Another solution is use the Convert.ToString method:
cboDeadlineType.Text = Convert.ToString(amendDiary.DeadlineType);
With that solution, if the input is null, the cboDeadlineType.Text is assigned exactly to null.
try
cboDeadlineType.Text = amendDiary.DeadlineType!=null ?amendDiary.ToString() :"";