VinnyGuitara
VinnyGuitara

Reputation: 605

Proper null check

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;

Upvotes: 0

Views: 750

Answers (2)

Dmytro Marchuk
Dmytro Marchuk

Reputation: 476

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.

Upvotes: 2

David
David

Reputation: 218877

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;

Upvotes: 3

Related Questions