Click here to Skip to main content
12,405,498 members (64,636 online)
Rate this:
 
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
Updated 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 6-Feb-13 7:46am
   
My apologies - didn't see your response before I posted mine
digimanus 6-Feb-13 7:51am
   
No problem! As long as the questioner undersands the answer
cyberist 6-Feb-13 8:00am
   
Does that mean that the teacher will be created each time i call the getter?
digimanus 6-Feb-13 8:02am
   
if it does not exist
Ankur\m/ 6-Feb-13 8:09am
   
There wasn't much difference in both the answer's time. 5!
boogac 6-Feb-13 9:10am
   
any idea about this operator's performance?
digimanus 6-Feb-13 9:34am
   
no, do you?
boogac 6-Feb-13 9:45am
   
no but i will try some little performance tests, it seemed to me useful..anyway,thanks for tip
digimanus 6-Feb-13 9:45am
   
you are welcome!
cyberist 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 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 6-Feb-13 7:51am
   
My 5!
Ankur\m/ 6-Feb-13 8:08am
   
And my 5 too!
Kishor Deshpande 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
Top Experts
Last 24hrsThis month


Advertise | Privacy | Mobile
Web02 | 2.8.160721.1 | Last Updated 6 Feb 2013
Copyright © CodeProject, 1999-2016
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