Easier way of writing null or empty?

前端 未结 5 391
失恋的感觉
失恋的感觉 2020-11-29 12:22

I\'m sure I\'ve missed something here. With a certain project I need to check if a string is empty or null.

Is there an easier way of writing this?

i         


        
5条回答
  •  我在风中等你
    2020-11-29 12:44

    if (string.IsNullOrEmpty(myString)) {
      ...
    }
    

    Or you could take advantage of a quirk in extension methods, they allow this to be null:

    static class Extensions {
        public static bool IsEmpty(this string s) {
            return string.IsNullOrEmpty(s);
        }
    }
    

    which then lets you write:

    if (myString.IsEmpty()) {
      ...
    }
    

    Although you probably should pick another name than 'empty'.

提交回复
热议问题