2

Im trying to understand mobile programming and then I came across this code for a method which is supposed to translate a character to a number. The code is working but my question is what is the purpose of the "?" after the int.

static int? Translate(char c)
        {
            if ("ABC".Contains(c))
                return 2;
            else if ("DEF".Contains(c))
                return 3;
            else if ("GHI".Contains(c))
                return 4;
            else if ("JKL".Contains(c))
                return 5;
            else if ("MNO".Contains(c))
                return 6;
            else if ("PQRS".Contains(c))
                return 7;
            else if ("TUV".Contains(c))
                return 8;
            else if ("WXYZ".Contains(c))
                return 9;

            return null;

        }
datachat
  • 51
  • 7

3 Answers3

3

? is syntax sugar for the Nullable<> class -- in your case int? is actually Nullable<Int32>.

The purpose of this class is to allow value types to represent null values, since they normally can't (they're "stack" objects in C++ terms). It involves boxing however so use them only when needed, there is a performance cost associated with it.

Also note that setting that to null (through return in your case, or just a normal assignment) doesn't actually set the reference to null. This is more compiler magic that actually sets it to new int?(), an instance with the HasValue property set to false.

Blindy
  • 65,249
  • 10
  • 91
  • 131
0

You can express that a value type is nullable in two ways:

  1. nullable ,nullable , etc

  2. int? double?

The question mark is only a shorthand.

Jesus Angulo
  • 2,646
  • 22
  • 28
0

int? is just shorthand for nullable<int>. A nullable datatype is one that can represent either it's type (int is this case) or null. 32-bit integers represent any number is the following range: -2,147,483,648 to 2,147,483,647; but nullable integers (int?) can be anything in that range, or null.

RobertR
  • 745
  • 9
  • 27