Click here to Skip to main content
15,881,204 members
Please Sign up or sign in to vote.
5.00/5 (3 votes)
See more:
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
Updated 6-Feb-13 6:55am
v3

This is called coalescing.
When this.teacher is NULL return a new teacher() object;
 
Share this answer
 
Comments
CHill60 6-Feb-13 7:46am    
My apologies - didn't see your response before I posted mine
Herman<T>.Instance 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?
Herman<T>.Instance 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!
?? 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
 
Share this answer
 
Comments
Herman<T>.Instance 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 :)
Your example code is idiomatic C# code to say
C#
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
C#
return teacher != null ? teacher : (teacher = new Teacher());

Cheers
Andi
 
Share this answer
 

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



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900