C# developers have always used throw statement to throw unhandled exceptions to caller. A reactive programming approach involved validating the variable values and if it doesn’t fall within a valid range or is null throw exception as demonstrated in below example
//Method that fetches data from server object Getdata() { //Fetch data from server or database and if data is null return null return null;// } private void btnThrowExpressionAlternateC6_Click(object sender, EventArgs e) { var data = Getdata(); if (data == null) throw new Exception("No Data found"); }
style="display:block; text-align:center;"
data-ad-format="fluid"
data-ad-layout="in-article"
data-ad-client="ca-pub-5021110436373536"
data-ad-slot="9215486331">
As you can see if data is null we create a custom exception and throw to caller. A shorthand syntax would have been to use null coalescing operator (??) to check if GetData method returns null and throw exception but since throw is a statement below syntax didn’t work in older versions of C# but it does in C# 7.0
private void btnThrowExpressionAlternateC7_Click(object sender, EventArgs e) { //Short and Concise . We cannot do that in C# 6 since ?? operator requires types on left hand side and right hand //side to be identical but with expressions this is supported var data = Getdata() ?? throw new Exception("No Data found"); }
All code samples are available at my GitHub profile
I am a corporate trainer and solution architect and have a great team of software professionals. Please contact in case you need our services by sending email to contact@techprocompsoft.com. Here is our company website .