C#에서 문자열이, 공백문자(White Space)나 Null인지 확인하는 함수
if (String.IsNullOrWhiteSpace(strSearch))
참고로 해당 함수는 .NET 4.0에서 지원.
The correct way in .NET 4.0 is:
if (String.IsNullOrWhiteSpace(strSearch))
The String.IsNullOrWhiteSpace
method used above is equivalent to:
if (strSearch == null || strSearch == String.Empty || strSearch.Trim().Length == 0)
// String.Empty is the same as ""
Reference for IsNullOrWhiteSpace method
http://msdn.microsoft.com/en-us/library/system.string.isnullorwhitespace.aspx
Indicates whether a specified string is Nothing, empty, or consists only of white-space characters.
In earlier versions, you could do something like this:
if (String.IsNullOrEmpty(strSearch) || strSearch.Trim().Length == 0)
The String.IsNullOrEmpty
method used above is equivalent to:
if (strSearch == null || strSearch == String.Empty)
Which means you still need to check for your "IsWhiteSpace" case with the .Trim().Length == 0
as per the example.
Reference for IsNullOrEmpty method
http://msdn.microsoft.com/en-us/library/system.string.isnullorempty.aspx
Indicates whether the specified string is Nothing or an Empty string.
Explanation:
You need to ensure strSearch
(or any variable for that matter) is not null
before you dereference it using the dot character (.
) - i.e. before you do strSearch.SomeMethod()
or strSearch.SomeProperty
you need to check that strSearch != null
.
In your example you want to make sure your string has a value, which means you want to ensure the string:
- Is not null
- Is not the empty string (
String.Empty
/""
) - Is not just whitespace
In the cases above, you must put the "Is it null?" case first, so it doesn't go on to check the other cases (and error) when the string is null
.
참고: https://stackoverflow.com/questions/8206810/object-reference-not-set-to-an-instance-of-an-object
'C#' 카테고리의 다른 글
Visual Studio 2017 CodeLens (VS Ultimate 2013이상, VS 2017 Pro이상) (0) | 2018.01.03 |
---|---|
C# 솔루션, 프로젝트 Project Template로 만들기 (0) | 2017.12.22 |
c# ComboBox 리스트 추가하기 (중복없이, 초기화) (0) | 2017.12.20 |
[C#] C#에서 Log4.net 사용 방법 (Log4net로 로그 파일 만들기) (0) | 2017.12.06 |
C# 코딩 규칙 (0) | 2017.11.23 |
C#에서 BackgroundWorker를 사용하기 (0) | 2017.10.06 |
C# SqlCommand 클래스 + ExecuteXmlReader (0) | 2017.10.03 |
long? 형식은 nullable 가능하게 됨 ( null값 허용 ) (0) | 2017.09.29 |
(로그인하지 않으셔도 가능)