Click here to Skip to main content
Rate this: bad
Please Sign up or sign in to vote.
See more: C#
Hello guys, could you tell me what is this? I saw this in an article.
        public Person Teacher
                return this.teacher ?? (this.teacher = new Teacher()); 
I have no idea what is this??
Posted 6-Feb-13 2:39am
Edited 6-Feb-13 7:55am
Rate this: bad
Please Sign up or sign in to vote.

Solution 1

This is called coalescing.
When this.teacher is NULL return a new teacher() object;
CHill60 at 6-Feb-13 7:46am
My apologies - didn't see your response before I posted mine
digimanus at 6-Feb-13 7:51am
No problem! As long as the questioner undersands the answer
cyberist at 6-Feb-13 8:00am
Does that mean that the teacher will be created each time i call the getter?
digimanus at 6-Feb-13 8:02am
if it does not exist
Ankur\m/ at 6-Feb-13 8:09am
There wasn't much difference in both the answer's time. 5!
boogac at 6-Feb-13 9:10am
any idea about this operator's performance?
digimanus at 6-Feb-13 9:34am
no, do you?
boogac at 6-Feb-13 9:45am
no but i will try some little performance tests, it seemed to me useful..anyway,thanks for tip
digimanus at 6-Feb-13 9:45am
you are welcome!
cyberist at 6-Feb-13 12:53pm
It means when null then return (this.teacher = new Teacher()). Does compiler know to wait till teacher gets initialized and then to return the instance?
digimanus at 8-Feb-13 3:34am
Rate this: bad
Please Sign up or sign in to vote.

Solution 2

?? Is the null coalescing operator - microsoft reference[^]
So the piece of code is essentially saying return the current instance of teacher, or if the current instance is null create one
digimanus at 6-Feb-13 7:51am
My 5!
Ankur\m/ at 6-Feb-13 8:08am
And my 5 too!
Kishor Deshpande at 6-Feb-13 9:26am
My 5 :)
Rate this: bad
Please Sign up or sign in to vote.

Solution 4

Your example code is idiomatic C# code to say
if (teacher == null)        // this is the part *before* the "??" coalescing operator
   teacher = new Teacher(); // this is the part *after* the "??" coalescing operator
return teacher;
return teacher != null ? teacher : (teacher = new Teacher());

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
0 CHill60 210
1 Sergey Alexandrovich Kryukov 200
2 Peter Leow 170
3 Richard Deeming 166
4 Zoltán Zörgő 135
0 Sergey Alexandrovich Kryukov 9,278
1 OriginalGriff 6,806
2 Peter Leow 4,432
3 Zoltán Zörgő 3,944
4 Richard MacCutchan 2,782

Advertise | Privacy | Mobile
Web02 | 2.8.150129.1 | Last Updated 6 Feb 2013
Copyright © CodeProject, 1999-2015
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100