Click here to Skip to main content
15,896,300 members
Articles / Programming Languages / C#

Conditional Operators Shortcuts

Rate me:
Please Sign up or sign in to vote.
1.50/5 (2 votes)
19 Jan 2013CPOL 0  
Use switch statementswitch (value){ case 6: case 8: case 10: size1 = value; break;}or if you really want to do this create extension method.static class Extensions{ public static bool In(this T value, params T[] values) { if (values...

Alternatives

Members may post updates or alternatives to this current article in order to show different approaches or add new features.

Please Sign up or sign in to vote.
19 Jan 2013PIEBALDconsult
Here's another way:private enum MySet{ Six = 6, Eight = 8, Ten = 10}if ( System.Enum.IsDefined ( typeof(MySet) , i ) )
Please Sign up or sign in to vote.
19 Jan 2013Gilmore Sacco 4 alternatives  
Dear experts,This will only take you 1 min max. I need to make a multiple conditional OR statement in a if statement. I know I can or them seperately, but is there a shortcut. This is my failed attempt:if (value == (6 || 8 || 10)){ size1 = value;}
Please Sign up or sign in to vote.
19 Jan 2013Thomas Daniels
Hi,I found this:if ((value | 6 | 8 | 10) == (6 | 8 | 10) && value != 0){ size1 = value;}In this case, there's no many difference in length of your condition. If you've variables with long names, or if many options are possible, this is a shorter condition.Alternatively,...
Please Sign up or sign in to vote.
19 Jan 2013PIEBALDconsult
No.But you could use a HashSetif ( new System.Collections.Generic.HashSet ( new int[] { 6 , 8 , 10 } ).Contains ( value ) )Though if you did that you should make the HashSet a static readonly field.I also wonder what you want to do when the value isn't in the set?

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Technical Lead Eyepax IT Consulting (Pvt) Ltd.
Sri Lanka Sri Lanka
Having more than 9 year hands-on industry experience in software development
Responsible for designing, implementing and managing complex software systems with stringent up-time requirement.

Visit my blog

Comments and Discussions