How to convert sbyte to string?

B M-A 361 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,

Developer technologies Windows Presentation Foundation
Developer technologies C#
0 comments No comments
{count} votes

Accepted answer
  1. Viorel 122.5K 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 30,126 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

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.