Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why the if condition doesn't check the nulls

Tags:

string

c#

.net

I was trying to check the null in my var but it throws "Object reference not set to an instance of an object."

 private void GenerateImage()
    {
        //Webster.Client.Modules.Metadata.Helper test = new Webster.Client.Modules.Metadata.Helper();
         var selectedstory = Webster.Client.Modules.Metadata.Helper.SelectedStoryItem;

        if((selectedstory.Slug).Trim()!=null)
        {
         //if (!string.IsNullOrEmpty(selectedstory.Slug))
       //{

           if (File.Exists(pathToImage))
           {
              }
           else
           {
               this.dialog.ShowError("Image file does not exist at the specified location", null);
           }
       }
       else
       {
           this.dialog.ShowError("Slug is Empty,please enter the Slug name", null);
       }
    }

I know selectedstory.Slug has the null value, which is why I used an if condition to check, but it's throwing right there in the if condition.

Can some one please advise what is the right way to check.

like image 230
Usher Avatar asked Nov 17 '25 20:11

Usher


1 Answers

You can't call methods on a null reference. Take out the .Trim().

like image 102
Joe White Avatar answered Nov 19 '25 09:11

Joe White



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!