Click here to Skip to main content
Rate this: bad
good
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
        {
            get
            {
                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
v3
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 1

This is called coalescing.
When this.teacher is NULL return a new teacher() object;
  Permalink  
Comments
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
   
yup
Rate this: bad
good
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
  Permalink  
Comments
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
good
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;
Or
return teacher != null ? teacher : (teacher = new Teacher());
Cheers
Andi
  Permalink  

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

  Print Answers RSS
0 Nirav Prabtani 268
1 OriginalGriff 217
2 Mika Wendelius 185
3 Sergey Alexandrovich Kryukov 176
4 CPallini 170
0 Nirav Prabtani 284
1 OriginalGriff 217
2 Mika Wendelius 185
3 _Amy 170
4 CPallini 170


Advertise | Privacy | Mobile
Web04 | 2.8.140721.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