Click here to Skip to main content
14,926,097 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
I have a problem.
Sometimes in .net when we use a function like
search_text(text, from_position, options)

we are forced to use multiple options in the "options" field like match case, search direction, etc.
How do we combine options in the flags?
I've used the AND operator:
search_text("aditya", 0, search.matchcase And search.dir_up)

But it does not work. Why is this?
Updated 19-Dec-09 8:25am

Assuming that "option" is an enum, use the "Or" operator. The enum will have to be defined in a manner which makes it suitable for this type of operation. For example, this would be suitable:
public enum SomeOptions
	FirstOption = 1,
	SecondOption = 2,
	ThirdOption = 4,
	FourthOption = 8,
	FifthOption = 16
	// Each time the number doubles.

This would not be suitable:
public enum SomeOptions
	FirstOption = 1,
	SecondOption = 2,
	ThirdOption = 3,
	FourthOption = 4,
	FifthOption = 5
	// Just add 1 to the number each time.

Using the "Flags" attribute just tells the compiler that you will be using this enum in the scenario you have described (combining various options). By doubling the numbers (1, 2, 4, 8, ...), you ensure that using the OR operator on them will produce valid results. The reason for that is how numbers are stored in binary. 1 is stored as "0001", 2 as "0010", 4 as "0100", 8 as "1000", and so on. If you combine 1 and 4, you get "0101" (i.e., the binary digits don't overlap).
raju melveetilpurayil 31-Jul-10 13:15pm
great presentation.

Thank you aspdotnetdev
Also, assuming you are working in C# (like your tag indicates), the "And" operator you are using is not valid. It is in VB, but not C#. In C#, the AND operator is "&" and the OR operator is "|". Those are arithmetic operations. Logical AND is "&&" and logical OR is "||". For enums, you want "|". For example:
search_text("aditya", 0, search.matchcase | search.dir_up);
In addition to the correct answer you already have, your 'option' enum should always have a value that equals 0
public enum MyOptions
    None = 0,
    // ...
in case no options are selected - this also serves as the default value!
Sergey Alexandrovich Kryukov 21-Dec-10 19:02pm
It's good to have, but no, this is not required because every enum value is compatible with 0.
This is legal:
MyOption option;
if (option == 0) {/* ... */}
DaveyM69 21-Dec-10 19:28pm
Not required, but highly recommended!
To specify multiple options with a single value, you need to bitwise add the options (having orthogonal values) by means of the OR operator.

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

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900