avoiding null reference exceptions

后端 未结 15 1012
天命终不由人
天命终不由人 2020-11-28 08:50

Apparently the vast majority of errors in code are null reference exceptions. Are there any general techniques to avoid encountering null reference errors?

Unless I

15条回答
  •  野性不改
    2020-11-28 09:15

    One of the most common null reference errors that I've seen is from strings. There will be a check:

    if(stringValue == "") {}
    

    But, the string is really null. It should be:

    if(string.IsNullOrEmpty(stringValue){}
    

    Also, you could be overly cautious and check an object isn't null before you attempt to access members/methods of that object.

提交回复
热议问题