5

I have a code containing a class with the following method:

public string AddEvent(DateTime date, int eventCount, int? eventId, string eventGuid){...}

My question is what does the question mark there do? My guess it has something to do with overloading since there's another overload method of AddEvent but I'm not sure...

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
O. San
  • 1,107
  • 3
  • 11
  • 25

2 Answers2

14

Simple, this isn’t C++ code. It’s C#, where ? denotes a nullable value type. I.e. a value type that can also be null. int? is a shortcut for Nullable<int>.

Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
2

Usually a simple type like int cannot be null, using ? allows the int to have a null value like an object.

Inside the function, you need to check to see if eventId is valid to use. You can do this by checking HasValue or equal to null. If you try to use it without checking, and it is null, then it will throw System.InvalidOperationException:

public string AddEvent(DateTime date, int eventCount, int? eventId, string eventGuid)
{
    // use HasValue
    if (eventId.HasValue)
        eventId++;

    // or check for null
    if (eventId != null)
        eventId++;
}
Greg Barlow
  • 198
  • 11