1. Back To Blog

C# and .NET interview questions on Coalescing operator.

When should we use "??" (NULL Coalescing operator) ?

"??" is a NULL coalescing operator. If you see the English meaning of coalescing it says "consolidate together". Coalescing operator returns the first NON-NULL value from a chain. For example below is a simple coalescing code which chains four strings.

So if "str1" is null it will try "str2" , if "str2" is null it will try "str3" and so on until it finds a string with a non-null value.

string final =str1 ??  str2 ?? str3 ?? str4;

What is the benefit of coalescing?

You do not need to write long if condition as shown below.

if (str1 != null)

                final = str1;

            }

            else

           

                if (str2 != null)

               

                    final = str2;

                }

                else

               

                    if (str3 != null)

                   

                        final = str3;

                    }

                    else

                   

                        if (str4 != null)

                       

                            final = str4;

                        }

                    }

                }

            }

This is a nice tutorial created by Questpond on Coalescing operator in c#.

Do not forget to watch below C#(CSharp) interview questions and answers series :-

Shiv Prasad Koirala

Visit us @ www.questpond.com or call us at 022-66752917... read more

We are on Social