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 1:39am
Edited 6-Feb-13 6: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 mhegazy94 460
1 Sergey Alexandrovich Kryukov 405
2 Kornfeld Eliyahu Peter 275
3 Gihan Liyanage 163
4 Sibeesh KV 156
0 Sergey Alexandrovich Kryukov 6,775
1 OriginalGriff 6,696
2 CPallini 5,345
3 George Jonsson 3,599
4 Gihan Liyanage 2,751

Advertise | Privacy | Mobile
Web04 | 2.8.140922.1 | Last Updated 6 Feb 2013
Copyright © CodeProject, 1999-2014
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