Congratulations to all monthly winners of May 2013 !!! They have won INR 2900 cash and INR 27497 worth prize.
Go to DotNetFunda.com
Twitter TwitterLinkedIn
YouTubeGoogle
 Online : 21457 |  Welcome, Guest!   Register  Login
Home > Articles > Best Practices > An introduction to Yoda Condition w.r.t. C#

An introduction to Yoda Condition w.r.t. C#

Article posted by Niladri.Biswas on 6/13/2012 | Views: 2108 | Category: Best Practices | Level: Beginner | Points: 250 red flag

Advertisements

Advertisements
In this article we will look into what are Yoda conditions and it's advantages w.r.t C#

Introduction

Many of us has the habit of writing the programming logic as follows

Case 1:

int a = 5;

if (a == 6){

//do something

}

or Case 2:

bool x = false;

if (x == true){

//do something

}

That means we are using equality comparison operator to compare the values.But, if by mistake we write like

Case 1:

int a = 5;

if (a = 6){

//do something

}

or Case 2:

bool x = false;

if (x = true){

//do something

}

Then the whole purpose of conditional checking will be wrong.

I do agree that for the first case, C# will give a compilation error Cannot implicitly convert type 'int' to 'bool'

while for the second case the it leaves away by giving an warning Assignment in conditional expression is always constant;did you mean to use == instead of = ?

The Yoda style

A better way to write code in that case will be in the Yoda style as below

Case 1:

int a = 5;

if (6 == a){

//do something

}

or Case 2:

bool x = false;

if (true == x){

//do something

}

Why?Because it reduces coding errors where we unintentionally mistyped the comparison operator == as a single =

Case 1:

int a = 5;

if (6 = a){

//do something

}

or Case 2:

bool x = false;

if (true = x){

//do something

}

C# will give compilation error in both the cases as

The left-hand side of an assignment must be a variable, property or indexer

In simple words,we can't assign a value to a literal

Usage of this conditions style was popular on C/C++ where we could assign value to variable when typed = instead of ==

Does it really needed in C#?

Well from all the above experiments (atleast Case 1), we have seen that in C# expressions are not converted automatically to bool and henceforth this practice does not make much sence in C# parlance

However,the convention should be to always put the constant on the left hand side of the expression so that an error can be statically detected at compile time in the event of a typo e.g. = (assignment) was coded instead of the == (equality).

How IL interpretes?

To answer this question, we have developed a simple program as under

public bool ConstantLeft(int a)

{

return a == 1;

}

public bool ConstantRight(int a)

{

return 1 == a;

}

When viewed in IL, we found the below for ConstantLeft() function

.method public hidebysig instance bool ConstantLeft(int32 a) cil managed

{

// Code size 10 (0xa)

.maxstack 2

.locals init ([0] bool CS$1$0000)

IL_0000: nop

IL_0001: ldarg.1

IL_0002: ldc.i4.1

IL_0003: ceq

IL_0005: stloc.0

IL_0006: br.s IL_0008

IL_0008: ldloc.0

IL_0009: ret

} // end of method Class1::ConstantLeft

For ConstantRight() function, IL view is as under

.method public hidebysig instance bool ConstantRight(int32 a) cil managed

{

// Code size 10 (0xa)

.maxstack 2

.locals init ([0] bool CS$1$0000)

IL_0000: nop

IL_0001: ldc.i4.1

IL_0002: ldarg.1

IL_0003: ceq

IL_0005: stloc.0

IL_0006: br.s IL_0008

IL_0008: ldloc.0

IL_0009: ret

} // end of method Class1::ConstantRight

The IL infers that, line numbers IL_0001 and IL_0002, they're just swapped but the order of the operands doesn't change the behavior of ceq at IL_0003.So apart from swapping, there was no change found.

Reference

What are yoda conditions?

Conclusion

Hope this little tip will be helpful. Comments and suggestions are welcome.

Thanks for reading.

Advertisements

If you like this article, subscribe to our RSS Feed. You can also subscribe via email to our Interview Questions, Codes and Forums section.

Page copy protected against web site content infringement by Copyscape
Found interesting? Add this to:



Please Sign In to vote for this post.

Experience:7 year(s)
Home page:http://www.dotnetfunda.com
Member since:Monday, October 25, 2010
Level:Diamond
Status: [Member]
Biography:Technical Lead at HCL Technologies Ltd., having 7 years of experience in IT field.
I love to explore new technologies and love challenges and try to help others as much as possible not only by coding but also by all possible means.
>> Write Response - Respond to this post and get points
Related Posts

This is last article of series for "Software patterns- GRASP" and we would summarize the discussions we had so far and conclude the series.

In OOAD, assignment of responsibilties to classes and objects is an inportant task and GRASP caters the guidelines for such assignments.

In this part of article for "Software patterns- GRASP", we would run through the process of assigning responsibilties of coordinating or controlling the system/ UI events.

In this part of article series for "Software patterns- GRASP", we would run through the process of assigning responsibilties so has to support low dependency and encourage resuse i.e. to implement the pattern "Low Coupling".

I have answered more than thirty questions on the different forums about the same subject. “How to Implement a flexible security module” , well the title differs from post to post but the question is the as the answer is the same. The Following post is the trigger or the valiant to the writing of this article.

More ...
About Us | Contact Us | The Team | Advertise | Software Development | Write for us | Testimonials | Privacy Policy | Terms of Use | Link Exchange | Members | Go Top
General Notice: If you find plagiarised (copied) contents on this page, please let us know the original source along with your correct email id (to communicate) for further action.
Copyright © DotNetFunda.Com. All Rights Reserved. Copying or mimicking the site design and layout is prohibited. Logos, company names used here if any are only for reference purposes and they may be respective owner's right or trademarks. | 6/19/2013 1:39:15 AM