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
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) {
- /* code(s) will execute if the bool condition is true */
- }
- else {
- /* code(s) will execute if the bool condition is false */
- }
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
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;
- }
- }
- }

Michael PerssonPosted Aug 16, 2022, 12:33 PM
Not sure if I am missing something or not but these 2 code snippets DO NOT do the same thing - The second snippet has a 30-20 condition with under 20 falling to NEED IMPROVEMENT where as a (Less Than) 20 condition in the first snippet will result in a FAIL response... I like the idea though and agree that more developers need to follow coding best practices.