Is my understanding of this piece of code correct?
I am reviewing the code from one of our contractors:
if (userLists != null)
{
Int32 numberOfItems = userLists.Count;
if ((numberOfItems & 1) == 1)
{
var emptyList = new tblList();
userLists.Add(emptyList);
}
}
Now, I'm trying to figure it out, so can someone please confirm with me if I succeeded or not?
- Do we have a userList instance?
- Yes. Get the number of elements in the userLists object.
- if (cardinality is 1 (yes / true) AND 1 is 1 (yes / true)) And this result is 1 (yes / true) and then adds an empty list object to the list.
- Else: nothing.
If so (WTFFFFFFFFFFFFFFFFFFFF !!!!!!!!!!), which can be refactored to
if (numberOfItems == 1)
{
..
}
but even that crap because I don't need a list with "empty" items.
So, did I read this piece of code correctly?
Oh, one more sigh when using Int32
vs Int
:( (but I digress).
a source to share
&
is what is called the bitwise operator. Whereas the operator &&
checks for two booleans:
TRUE && FALSE => FALSE
TRUE && TRUE => TRUE
operator &
can work with integer values:
00101101 (45)
& 01011011 (91)
---------------
= 00001001 (9)
Each bit performs logical operation (s) performed on it. So, in the case of your example code, it asks, "Is the last bit 1?" - that is, "is it weird?" For example, if the number is 23:
00010111 (23)
& 00000001 (1)
---------------
= 00000001 (1)
So it gets added to the list because 1 == 1. But if the number is 22:
00010110 (22)
& 00000001 (1)
---------------
= 00000000 (0)
Therefore, it is not added to the list.
a source to share
Checking odd, can also be done i % 2 != 0
I would suggest looking at BitMasks , they can be very handy, but not in the code of your question, I would prefer you had to do even / odd.
static void Main(string[] args)
{
for (int i = 0; i < 100; i++ )
Console.WriteLine( i & 1);
Console.ReadLine();
}
1
0
1
0
1
0
And for that, here are some extension methods
class Program
{
static void Main(string[] args)
{
List<int> ints = new List<int>();
for (int i = 0; i < 100; i++)
{
Console.WriteLine("Mod: {0}", i % 2 );
Console.WriteLine("BitWise: {0}", i & 1 );
ints.Add(i);
Console.WriteLine("Extension: {0}", ints.IsEven() );
}
Console.ReadLine();
}
}
public static class ListExtensions
{
public static bool IsEven<T>(this ICollection<T> collection)
{
return (collection.Count%2) == 0;
}
public static bool IsOdd<T>(this ICollection<T> collection)
{
return (collection.Count%2) != 0;
}
}
a source to share