skip to Main Content

I’m currently learning C#, I am a beginner, so I’m not really familiar with the particularities of this language.

My problem is:

I have this piece of code which is supposed to convert an INTEGER to a CHAR and add 55 to the INTEGER to obtain the ASCII code for the hexadecimal when the user chooses a base between 11 and 16. When I use a simple "if" and "else" it works perfectly well, but for some reason, it doesn’t work with the ternary operator


nConverti += (pNewbase > 10 && n >= 10) ?( n += 55 : (char)(n)): n;

nConverti += Depiler(ref unePile);  

Just for presision I’m currently using Visual Studio 2022 version 17.8.5 and the framework’s version is 4.8.09032.

I thank in advance anyone who will help me resolve this issue.

I already tried to read all the documentation I found about the ternary in C# but didn’t found any solution, I even asked my college teacher who wasn’t able to help me too. I also tried to update my framework and my visual studio but still doesn’t change (even if I don’t really think that the issue comes from there).

2

Answers


  1. The ternary operator works as follows: condition ? [true expression] : [false expression]

    nConverti += (pNewbase > 10 && n >= 10) ? (char)(n + 55) : (char)n;
    

    using the assignment operator += inside the ternary expression, which is not necessary and can lead to confusion better to write in if else and its upto you

    if (pNewbase > 10 && n >= 10)
    {
        nConverti += (char)(n + 55);
    }
    else
    {
        nConverti += (char)n;
    }
    
    Login or Signup to reply.
  2. I agree with all the others that the code as written is not syntactically correct. Also a little difficult from your description to make out the intent but.
    Nice to provide the Visual Studio and Framework versions but these are not all that important. Your code is just basic C# that should be compatible with all current versions of the language.

    int n = 11;
    int newBase = 10;
    string converti = "";
    converti += (newBase > 10 && n >= 10) ? (char)(n + 55) : (char)n;
    

    Above is what I think you are trying to do.
    A few things to note.
    The code that you have include has this phrase ( n += 55 : (char)(n)) but this is not a syntactically correct.
    I’ve replaced this with (char)(n + 55)

    It’s important to note that both values returned by the ternary operator must be the same type that is the result of a single expression.

    If we have misinterpreted your code, please add a little more context and also show the version of the code that is written using the if statement.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search