Computer >> 컴퓨터 >  >> 프로그래밍 >> C#

C# SByte.ToString() 메서드 완벽 정리 – 예제 코드와 실행 결과까지

C#에서 SByte.ToString() 메서드는 해당 인스턴스가 가진 숫자 값을 동일한 의미의 문자열 표현으로 변환할 때 사용됩니다. 부호 있는 8비트 정수인 sbyte 타입의 값을 화면에 출력하거나 문자열과 결합해야 할 때 매우 유용하게 활용할 수 있습니다.

문법(Syntax)

SByte.ToString() 메서드의 기본 문법은 다음과 같습니다.

public override string ToString();

이 메서드는 매개변수를 받지 않으며, 현재 sbyte 인스턴스의 숫자 값을 나타내는 string을 반환합니다.

예제 1

먼저 두 개의 sbyte 변수를 선언하고, ToString() 메서드를 사용해 문자열로 변환하는 기본적인 예제를 살펴보겠습니다.

using System;
public class Demo {
    public static void Main(){
        sbyte s1 = 10;
        sbyte s2 = 100;
        Console.WriteLine("Value of S1 = " + s1);
        Console.WriteLine("Value of S2 = " + s2);
        
        int res = s1.CompareTo(s2);
        if (res > 0)
            Console.WriteLine("s1 > s2");
        else if (res < 0)
            Console.WriteLine("s1 < s2");
        else
            Console.WriteLine("s1 = s2");
        
        Console.WriteLine("\nHashCode for s1 = " + s1.GetHashCode());
        Console.WriteLine("GetTypeCode for s1 = " + s1.GetTypeCode());
        Console.WriteLine("String representation for s1 = " + s1.ToString());
        
        Console.WriteLine("\nHashCode for s2 = " + s2.GetHashCode());
        Console.WriteLine("GetTypeCode for s2 = " + s2.GetTypeCode());
        Console.WriteLine("String representation for s2 = " + s2.ToString());
    }
}

실행 결과

위 코드를 실행하면 다음과 같은 결과가 출력됩니다.

Value of S1 = 10
Value of S2 = 100
s1 < s2
HashCode for s1 = 2570
GetTypeCode for s1 = SByte
String representation for s1 = 10
HashCode for s2 = 25700
GetTypeCode for s2 = SByte
String representation for s2 = 100

출력 결과에서 확인할 수 있듯이, ToString() 메서드는 sbyte 값인 10과 100을 각각 문자열 "10"과 "100"으로 변환하여 반환합니다. 또한 GetTypeCode() 메서드는 해당 값의 타입 코드가 SByte임을 보여줍니다.

예제 2

이번에는 SByte.MaxValue(127)를 활용하여 ToString() 메서드의 동작을 추가로 확인해 보겠습니다.

using System;
public class Demo {
    public static void Main(){
        sbyte s1 = 99;
        sbyte s2 = SByte.MaxValue;
        Console.WriteLine("Value of S1 = " + s1);
        Console.WriteLine("Value of S2 = " + s2);
        Console.WriteLine("Is s1 and s2 equal? = " + s1.Equals(s2));
        
        int res = s1.CompareTo(s2);
        if (res > 0)
            Console.WriteLine("s1 > s2");
        else if (res < 0)
            Console.WriteLine("s1 < s2");
        else
            Console.WriteLine("s1 = s2");
        
        Console.WriteLine("String representation for s1 = " + s1.ToString());
        Console.WriteLine("String representation for s2 = " + s2.ToString());
    }
}

실행 결과

위 예제의 출력 결과는 다음과 같습니다.

Value of S1 = 99
Value of S2 = 127
Is s1 and s2 equal? = False
s1 < s2
String representation for s1 = 99
String representation for s2 = 127

정리

SByte.ToString() 메서드는 sbyte 숫자 값을 문자열로 손쉽게 변환해 주는 기본적인 메서드입니다. 콘솔 출력, 로깅, UI 표시 등 다양한 상황에서 숫자 데이터를 문자열 형태로 다뤄야 할 때 널리 사용되므로, 위 예제들을 직접 실행해 보며 동작 방식을 익혀두는 것이 좋습니다.