1

Is there an operator in C# that behaves like the safe navigation operator in groovy?

For instance, in groovy, doing something like this will prevent it from getting a NullPointerException if SessionData.CurrentSeminar is null.

int respId = SessionData.CurrentSeminar?.SeminCbaRespId;

How is this accomplished with C#?

Jeff LaFay
  • 12,882
  • 13
  • 71
  • 101
kbaccouche
  • 4,575
  • 11
  • 43
  • 65

4 Answers4

1

That operator does not exist in C#. You could do it with an inline-if

int respId = SessionData.CurrentSeminar != null ? 
   SessionData.CurrentSeminar.SeminCbaRespId : default(int);

or as an extension method.

var respId = SessionData.CurrentSeminar.GetSeminCbaRespId();

public static int GetSeminCbaRespId(this typeofCurrentSeminar CurrentSeminar)
{
   return CurrentSeminar != null ? CurrentSeminar.SeminCbaRespId : default(int);
}
Daniel A. White
  • 187,200
  • 47
  • 362
  • 445
  • This seems to be a good workaround, thanks. It's weired that such a perfect operator does not exist in C#. – kbaccouche Apr 16 '12 at 13:10
  • http://connect.microsoft.com/VisualStudio/feedback/details/192177/a-bit-more-c-syntactic-sugar-for-nulls – Daniel A. White Apr 16 '12 at 13:11
  • http://stackoverflow.com/a/2081709/33080 - it’s Eric’s standard answer. We want this, but we can’t implement everything due to time constraints. – Roman Starkov Apr 16 '12 at 13:12
0

Maybe workaround like this?

int respId= ReferenceEquals(SessionData.CurrentSeminar,null)?-1:SessionData.CurrentSeminar.SeminCbaRespId;
Rami Alshareef
  • 7,015
  • 12
  • 47
  • 75
0

There is no operator for this, but you can get close. Try the one from this answer:

int respId = SessionData.CurrentSeminar.NullOr(s => s.SeminCbaRespId) ?? 0;

This gets extra useful if you need to chain several of them:

var elem = xml.Element("abc")
    .NullOr(x => x.Element("def"))
    .NullOr(x => x.Element("blah");
Community
  • 1
  • 1
Roman Starkov
  • 59,298
  • 38
  • 251
  • 324
0

The closest operator is ?:, but it's not as sugary.
So, you could do:

int respId = SessionData.CurrentSeminar != null ? SessionData.CurrentSeminar.SeminCbaRespId : 0; // if 0 is the "null" value 
Jeff LaFay
  • 12,882
  • 13
  • 71
  • 101
Steve Wong
  • 2,038
  • 16
  • 23