Introduction
In this blog, we will learn the best practice to use if else condition in C#.I have seen more than 10+ projects based on asp.net C# which are developed by experienced developer,s but I think most of the developers are not following best practices of C# coding standards due to which I have decided to write this blog.
Kindly find the screenshot in regards to If else condition.
As per the image, if else condition is used to check if any object value is true or false, because it will take bool value.
By default, if else returns true.
Syntax
- if(booleanExpression) {
-
- }
- else {
-
- }
In this syntax, we can see, if condition is true then if block code will be executed otherwise else block will execute.
See the example
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
-
- namespace CsharpCorner
- {
- class Program
- {
- static void Main()
- {
- string result = Calculate(100);
- Console.Write(result);
- Console.Read();
- }
-
- public static string Calculate(int TotalMarks)
- {
- string result = null;
- if (TotalMarks < 30)
- {
- result = "fail!!!!";
- }
- else if (TotalMarks > 30)
- {
-
- result = "Pass";
- }
- else
- {
- result = "Need improvement!!!";
- }
-
- return result;
-
-
- }
- }
- }
I think instead of these multiple lines of code, we can write only a single line of code.
This code can be re-written, as shown below. This is called best practices of C# code .e.g.
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
-
- namespace CSharpCornerTest
- {
- class Program
- {
- static void Main()
- {
- string result = Calculate(24);
- Console.Write(result);
- Console.Read();
- }
-
- public static string Calculate(int TotalMarks)
- {
- string result = null;
-
- result = TotalMarks < 30 && TotalMarks>20
- ? "Fail!!!!"
- : TotalMarks > 30
- ? "Pass"
- : "Need improvment";
- return result;
-
-
- }
- }
- }
We can see this can perform same action in a single line of code.
Whatever I have explained with you all, we can use in JavaScript, jQuery, Angularjs. etc. In any type of programming language, always try to use best practices.
Advantage of best practice of programming
- Can reduce line of code.
- Easy to understand.
- Easy to change.
- Performance can be improved.
- Code will always look clean.
I hope, this blog will be helpful for freshers and professionals.