Programing

문자열 유형의 기본값이 빈 문자열 대신 널인 이유는 무엇입니까?

lottogame 2020. 5. 5. 19:31
반응형

문자열 유형의 기본값이 빈 문자열 대신 널인 이유는 무엇입니까?


등의 null메소드를 안전하게 적용하기 전에 모든 문자열을 테스트하는 것은 상당히 성가신 ToUpper()일입니다 StartWith().

기본값이 경우 string빈 문자열 있었다, 나는 시험이없는 것, 그리고 내가 좋아하는 다른 값 유형과 일관성을 위해 그것을 느낄 것 int또는 double예를 들어. 또한 Nullable<String>의미가 있습니다.

그렇다면 C #의 디자이너 null가 문자열의 기본값 으로 사용하기 선택한 이유는 무엇입니까?

참고 : 이것은 이 질문관련 있지만 질문관련하여 대신 이유에 더 중점을 둡니다.


문자열 유형의 기본값이 빈 문자열 대신 널인 이유는 무엇입니까?

때문에 stringA는 참조 형 과 기본 값은 모든 참조 형식입니다 null.

ToUpper (), StartWith () 등과 같은 메소드를 안전하게 적용하기 전에 모든 문자열을 null로 테스트하는 것은 상당히 성가신 일입니다.

이는 참조 유형의 동작과 일치합니다. 인스턴스 멤버를 호출하기 전에 null 참조를 확인해야합니다.

string의 기본값이 빈 문자열이라면 테스트 할 필요가 없으며 int 또는 double과 같은 다른 값 유형과 더 일관성이 있다고 생각합니다.

이외의 특정 참조 유형 기본값 지정 null은 할 것 일관성을 .

또한 Nullable<String>의미가 있습니다.

Nullable<T>값 유형과 함께 작동합니다. 참고로 사실이다 Nullable원본에 소개되지 않은 .NET 플랫폼 깨진 코드를 많이들이 그 규칙을 변경했다가되었을 것이다, 그래서이. ( 의례의 @jcolebrand )


Habib이 맞습니다 string. 참조 유형 이기 때문 입니다.

그러나 더 중요한 것은 사용할 때마다 확인할 필요가 없습니다null . 그래도 ArgumentNullException누군가가 함수에 null참조를 전달 하면를 던져야합니다 .

여기에 문제 NullReferenceException가 있습니다. 어쨌든 .ToUpper()문자열 을 호출하려고하면 프레임 워크가 대신 합니다. null매개 변수로 평가 될 수 있으므로 함수에 전달 된 객체의 속성이나 메서드는 인수를 테스트하더라도이 경우가 여전히 발생할 수 있습니다 null.

존재가 말했다, 빈 문자열 또는 null을 확인하는 것이 할 수있는 일반적인 일이, 그들이 제공하는 그래서 String.IsNullOrEmpty()String.IsNullOrWhiteSpace()단지 이러한 목적을 위해.


확장 방법을 작성할 수 있습니다 (가치있는 것).

public static string EmptyNull(this string str)
{
    return str ?? "";
}

이제 이것은 안전하게 작동합니다.

string str = null;
string upper = str.EmptyNull().ToUpper();

C # 6.0에서 다음을 사용할 수도 있습니다.

string myString = null;
string result = myString?.ToUpper();

문자열 결과는 null입니다.


빈 문자열과 null은 근본적으로 다릅니다. null은 값이없고 빈 문자열은 비어있는 값입니다.

변수의 "값"에 대해 가정하는 프로그래밍 언어 (이 경우 빈 문자열)는 null 참조 문제를 일으키지 않는 다른 값으로 문자열을 시작하는 것만 큼 좋습니다.

또한 해당 문자열 변수의 핸들을 응용 프로그램의 다른 부분으로 전달하면 의도적으로 빈 값을 전달했는지 또는 해당 변수의 값을 채우는 것을 잊었는지 여부를 확인할 수있는 방법이 코드에 없습니다.

이것이 문제가되는 또 다른 경우는 문자열이 일부 함수의 반환 값 인 경우입니다. string은 참조 유형이며 기술적으로 null 및 비어있는 값을 가질 수 있으므로 함수는 기술적으로 null 또는 비어있는 값을 리턴 할 수 있습니다 (그렇게하는 것을 막을 방법은 없습니다). 이제 "값 없음"이라는 두 가지 개념, 즉 빈 문자열과 null이 있으므로이 함수를 사용하는 모든 코드는 2 개의 검사를 수행해야합니다. 하나는 비어 있고 다른 하나는 널입니다.

요컨대, 항상 단일 상태에 대해 하나의 표현 만 갖는 것이 좋습니다. 빈 및 널에 대한보다 자세한 내용은 아래 링크를 참조하십시오.

https://softwareengineering.stackexchange.com/questions/32578/sql-empty-string-vs-null-value

사용자 입력을 처리 할 때 NULL 대 비어 있음


The fundamental reason/problem is that the designers of the CLS specification (which defines how languages interact with .net) did not define a means by which class members could specify that they must be called directly, rather than via callvirt, without the caller performing a null-reference check; nor did it provide a meany of defining structures which would not be subject to "normal" boxing.

Had the CLS specification defined such a means, then it would be possible for .net to consistently follow the lead established by the Common Object Model (COM), under which a null string reference was considered semantically equivalent to an empty string, and for other user-defined immutable class types which are supposed to have value semantics to likewise define default values. Essentially, what would happen would be for each member of String, e.g. Length to be written as something like [InvokableOnNull()] int String Length { get { if (this==null) return 0; else return _Length;} }. This approach would have offered very nice semantics for things which should behave like values, but because of implementation issues need to be stored on the heap. The biggest difficulty with this approach is that the semantics of conversion between such types and Object could get a little murky.

An alternative approach would have been to allow the definition of special structure types which did not inherit from Object but instead had custom boxing and unboxing operations (which would convert to/from some other class type). Under such an approach, there would be a class type NullableString which behaves as string does now, and a custom-boxed struct type String, which would hold a single private field Value of type String. Attempting to convert a String to NullableString or Object would return Value if non-null, or String.Empty if null. Attempting to cast to String, a non-null reference to a NullableString instance would store the reference in Value (perhaps storing null if the length was zero); casting any other reference would throw an exception.

Even though strings have to be stored on the heap, there is conceptually no reason why they shouldn't behave like value types that have a non-null default value. Having them be stored as a "normal" structure which held a reference would have been efficient for code that used them as type "string", but would have added an extra layer of indirection and inefficiency when casting to "object". While I don't foresee .net adding either of the above features at this late date, perhaps designers of future frameworks might consider including them.


Because a string variable is a reference, not an instance.

Initializing it to Empty by default would have been possible but it would have introduced a lot of inconsistencies all over the board.


Why the designers of C# chose to use null as the default value of strings?

Because strings are reference types, reference types are default value is null. Variables of reference types store references to the actual data.

Let's use default keyword for this case;

string str = default(string); 

str is a string, so it is a reference type, so default value is null.

int str = (default)(int);

str is an int, so it is a value type, so default value is zero.


If the default value of string were the empty string, I would not have to test

Wrong! Changing the default value doesn't change the fact that it's a reference type and someone can still explicitly set the reference to be null.

Additionally Nullable<String> would make sense.

True point. It would make more sense to not allow null for any reference types, instead requiring Nullable<TheRefType> for that feature.

So why did the designers of C# choose to use null as the default value of strings?

Consistency with other reference types. Now, why allow null in reference types at all? Probably so that it feels like C, even though this is a questionable design decision in a language that also provides Nullable.


Perhaps if you'd use ?? operator when assigning your string variable, it might help you.

string str = SomeMethodThatReturnsaString() ?? "";
// if SomeMethodThatReturnsaString() returns a null value, "" is assigned to str.

A String is an immutable object which means when given a value, the old value doesn't get wiped out of memory, but remains in the old location, and the new value is put in a new location. So if the default value of String a was String.Empty, it would waste the String.Empty block in memory when it was given its first value.

Although it seems minuscule, it could turn into a problem when initializing a large array of strings with default values of String.Empty. Of course, you could always use the mutable StringBuilder class if this was going to be a problem.


Since string is a reference type and the default value for reference type is null.


Maybe the string keyword confused you, as it looks exactly like any other value type declaration, but it is actually an alias to System.String as explained in this question.
Also the dark blue color in Visual Studio and the lowercase first letter may mislead into thinking it is a struct.


Nullable types did not come in until 2.0.

If nullable types had been made in the beginning of the language then string would have been non-nullable and string? would have been nullable. But they could not do this du to backward compatibility.

A lot of people talk about ref-type or not ref type, but string is an out of the ordinary class and solutions would have been found to make it possible.

참고URL : https://stackoverflow.com/questions/14337551/why-is-the-default-value-of-the-string-type-null-instead-of-an-empty-string

반응형