How to convert sbyte to string?

B M-A 321 Reputation points
2022-11-12T11:24:51.87+00:00

Hello,

I have a table with two sbyte values 1 and 0 .
I want to return from a query string instead of sbyte .
For example : I want to return "finished" for 1 and "unfinished" for 0.

status.Value == 1 ? "Finished" : status.Value == 0 ? "Unfinished" : status.Value  

I get this error "Cannot implicitly convert type 'string' to 'sbyte' "

Best regards,

Windows Presentation Foundation
Windows Presentation Foundation
A part of the .NET Framework that provides a unified programming model for building line-of-business desktop applications on Windows.
2,373 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
8,246 questions
0 comments No comments
{count} votes

Accepted answer
  1. Viorel 95,261 Reputation points
    2022-11-12T12:45:12.837+00:00

    Try this:

    status.Value == 0 ? "Unfinished" : "Finished"

    or this:

    status.Value == 1 ? "Finished" : status.Value == 0 ? "Unfinished" : status.Value.ToString( )

    In modern C#:

    status.Value switch { 1 => "Finished", 0 => "Unfinished", _ => status.Value.ToString( ) }


1 additional answer

Sort by: Most helpful
  1. AgaveJoe 22,801 Reputation points
    2022-11-12T12:58:31.73+00:00

    The error is extremely clear but your design is very confusing and incomplete. The nullable sbyte type (signed byte) has 256 different values and null while your design is looking for a 0 or 1 and does not check for null.

    What happens if the value is null or a value other than 1 or 0? Perhaps an Enum is a better design approach?

    Enumeration types (C# reference)

    Example code. Rather than a static method you could take advantage of an extension method. Rather than an if you could use a case.

        public static async Task Main()  
        {  
      
            sbyte? status = null;  
      
            string result = GetStatus(status);  
            Console.WriteLine($"Result: {result}");  
      
            status = 1; result = GetStatus(status);  
            Console.WriteLine($"Result: {result}");  
      
            status = 0; result = GetStatus(status);  
            Console.WriteLine($"Result: {result}");  
      
            status = 10; result = GetStatus(status);  
            Console.WriteLine($"Result: {result}");  
      
            status = -10; result = GetStatus(status);  
            Console.WriteLine($"Result: {result}");  
        }  
      
        public static string GetStatus(sbyte? status)  
        {  
            if (status.HasValue)  
            {  
                if(status.Value == 0) { return "Unfinished"; }  
                if (status.Value == 1) { return "Finished"; }  
            }  
      
            return string.Empty;  
        }  
    
    0 comments No comments