Archives for : often unused operators

Often Unused Operators: fixed()

This post is inspired by Eric Clippert’s post on References and Pointers.

I think it escapes a lot of C# devs that they have the same pointer abilities as C/C++, or maybe it’s that those features have been intentionally down-played by Microsoft for a reason. As C# devs we’ve come to rely on nice, safe and managed code and GC. That doesn’t mean we can’t cause an out of memory exception or infinite recursion or some other bad thing along the way, but for the most part C# tries to protect us. While I’m not going to cover pointers (something of which I have a fondness for given that my very first college class was “Fundamentals of C”) I do want to go over the fixed() operation.

Fixed is basically telling the GC, “Don’t move me, don’t touch me, don’t GC me, don’t even look at me” which is why fixed can only be used within an unsafe context. It’s important to mention that unsafe means, um, unsafe. When you identify an area of code as unsafe you’re saying, “Hey, I know I’m doing something that could potientially be really bad and all the work MS has done to try and protect me I’m ignoring. I really, really promise to only use smart code here.”

Here’s a bit of code using fixed:

unsafe void FixedExample()
{
    double[] arr = { 0, 1.5, 3, 4.5, 6, 7.5, 9 };
    fixed(double* p1 = &arr[1])
    {
        fixed (double* p2 = &arr[5])
        {
            int diff = (int)(p2 - p1);
            Debug.Print(diff.ToString());
        }
    }
}
unsafe void FixedExample2()
{
    double[] array =  { 0, 1.5, 3, 4.5, 6, 7.5, 9 };
    fixed (double* arr = array)
    {
        double* p1 = &arr[1];
        double* p2 = &arr[3];
        int diff = (int)(p2 - p1);
        Debug.Print(diff.ToString());
    }
}

Basically, fixed allows you to get pointers to managed types which would otherwise be subjected to GC. If you were to work just with pointers and not managed types you can do the above (using stackalloc) without even needing fixed.

unsafe void StackallocExample()
{
    int arraySize = 7;
    double* arr = stackalloc double[arraySize];
    double j = 0;
    for (int i = 0; i < arraySize; i++, j += 1.5)
    {
        arr[i] = j;
    }

    double* p1 = &arr[1];
    double* p2 = &arr[15];
    int diff = (int)(p2 - p1);
    Debug.Print(diff.ToString());
}

but of course the above code is very bad. If you didn't notice, the second pointer points to the 16th element (since we're obviously 0 based) but I only allocated 7 doubles worth of memory. If I were do try and do something with arr[15] (rather then just determine the distance between the two elements) that would be very bad as it wouldn't represent a value I had intended and would just be some random bit of whatever was stored in that memory location. Interestingly enough, if you try the same in the first two examples you'll get a runtime exception.

Thanks,
Brian

Often Unused Operators: Curly Braces {}

Okay, I know you think I’ve seriously hit the crack pipe here. Curly Braces, as I’m sure we all know, are fundamental to programming in most languages. This is true no more so then here in C#. We use them for if, for, using, do, while, namespace scope, class scope, method scope and getters and setters for parameters.

So how could I dare to say the {} is an often unused operator? Well, I’m specifically talking about a use of the operators in this case, not the operators themselves.

Did you know you can use curly braces by themselves? Take a look at this:

public Window1()
{
    InitializeComponent();

    {
        int [] intList = { 1, 2, 3, 4, 5, 6 };
        var evens = intList.Where(x => x % 2 == 0);
    }

    {
        int[] intList = { 1, 2, 3, 4, 5, 6 };
        var odds = intList.Where(x => x % 2 == 1);
    }
}

Yes! That there are curly braces by themselves!

Why the hell would anyone want to do this? I find myself using them all the time when writing up samples where at http://www.formatexception.com. The reason is that I test all the sample code I post up here that I write. This has been a big help especially since it seems like a lot of the linq code here derives from msdn samples and, believe it or not, not all of them work.

What this means is that if I want to do a write-up on linq where I’m using the where method on IEnumerables (like above) I write the code surrounded by curly braces. Because each is it’s own scope, call it internal method scope if you will, there won’t be any name collisions. It’s like doing an if(true){} without the if(true), or like using the using keyword as in:

using(Stream ImageStream = new MemoryStream(File.ReadAllBytes(ImagePath)))
{
    BitmapImage bi = new BitmapImage();
    bi.BeginInit();
    bi.StreamSource = ImageStream;
    bi.EndInit();
    
    Image imageFromFile = new Image() { Source = bi };
    //dump image into wrap panel in form
    imagePanel.Children.Add(imageFromFile);
}

except you don’t have to have a class the implements IDisposable.

So, where would you use this? If you’re real paticular (i.e. anal) about the your variable names. For instace the following code is not valid:

{
    int [] intList = { 1, 2, 3, 4, 5, 6 };
    var evens = intList.Where(x => x % 2 == 0);
}


int[] intList = { 7, 8, 9, 10, 11, 12 };
var odds = intList.Where(x => x % 2 == 1);

The reason is that the set of curly braces define a child scope but the second intlist exists in the parent scope. Sibling scopes can have variables of the same name but not parent/child scopes. If I really wanted my intList to be named “intList” and assuming it would only be needed within the child scope I could put a second set of curly braces around the other code and be free to name my intList to, um, “intList”.

I have never really found a use for this in production code to be honest. I use it a lot when writing up samples for my posts, but not in production code. I suppose if I was adamant about my variable names I would use it more and I think a few of you out there are. I, however, have no problem simply naming my second int list to intListForOdds.

So that is the curly braces and their often unused purpose.

Later,
Brian

Often Unused Operators: checked and unchecked

From MSDN:
The checked keyword is used to explicitly enable overflow-checking for integral-type arithmetic operations and conversions.
By default, an expression that contains only constant values causes a compiler error if the expression produces a value that is outside the range of the destination type. If the expression contains one or more non-constant values, the compiler does not detect the overflow.

The unchecked keyword is used to suppress overflow-checking for integral-type arithmetic operations and conversions.
In an unchecked context, if an expression produces a value that is outside the range of the destination type, the overflow is not flagged.

Okay, so what the hell does this mean?
The C# compiler checks at compile time for overflow exceptions.
If you do:

int tooBig = 2147483647 + 10;

you get the error “The operation overflows at compile time in checked mode.” The problem arises when you use variables. Since a variable could be anything the compiler doesn’t check for overflows. If you do:

int ten = 10;
int tooBig = 2147483647 + ten;

your code will compile but the value of tooBig will be -2147483639. This is because default behavior of the runtime environment is to skip checking for overflows and your values just wrap.

So, what do you care?

Most likely you don’t. I’ll be honest. Chances are you’re not writing algoritms so important that if you overflow the world is going to come crashing down about you. Every once in awhile you do, however, come across some peace of critical software that may need to handle overflow exceptions. That is where the checked and unchecked operations come into play.

The problem is that checking every math operation for an overflow is slow. Okay, maybe slow is a bit much. It is, however, a couple of microseconds that you could be using on other things and it’s really slow if an overflow exception is thrown and you have to handle it. In math heavy operations and algorithms these few microseconds could add up to a lot of time so be sure that your code is critical enough that an overflow must be handled.

So, how do we fix this? We use the checked operation (in either the block or expression form).

//block
checked{
    int twenty = 10 + 10;
}
//expression
int thirty = checked(10 + 20);

This tells the compiler to check the numbers and if there is an overflow throw an overflow exception.

The opposite of the checked operator is unchecked:

//block
unchecked{
    int twenty = 10 + 10;
}
//expression
int thirty = unchecked(10 + 20);

This works just like the default behavior of not checking for overflows with variables. Since this is done automatically you probably won’t use this too often unless you start using the checked operator. The nice thing is that you can combine both checked and unchecked for the appropriate values.

unchecked
{
    int ten = 10;
    int tooBig = checked(2147483647 + ten);
    Console.WriteLine(i3);
}

yields an overflow exception being thrown since 2147483647 + ten overflows. Conversely,

checked
{
    int ten = 10;
    int tooBig = unchecked(2147483647 + ten);
    Console.WriteLine(i3);
}

results in a value of -2147483639 since the unchecked means the runtime environment to not check for overflow.

That’s all for now,
Brian

Often Unused Operators: |= (or equals)

I’ve debated before the usefulness of the | and & operators. The use of the | operator depends on the context in which it is used.

In the case of bools a boolean operation is performed. In the case of ints a bitwise OR is performed.

For boolean operations when the | operator is used both sides of the operator are evaluated. In the example below both VerifyStatus and SetDefaults are called regardless of the boolean returned by each of them.

public void TestTransaction(PaymentTransaction Transaction)
{
    if (Transaction != null && 
        (VerifyStatus(Transaction.State) | SetDefaults(Transaction)))
    {
        //do something with the code
    }
}
private bool VerifyStatus(ItemState State)
{
    if (State == null)
        return false;
    if (State.Status == Status.NotVerified)
        ValidateStatus(State);
    if (State.Status == Status.Valid)
        return true;
    //Status.Invalid
    return false;
}
private void ValidateStatus(ItemState State)
{
    //validate the status
}
private bool SetDefaults(PaymentTransaction Transaction)
{
    if (Transaction == null)
        return false;
    //no need to set the defaults if the state is already valid
    if (Transaction.State.Status == Status.Valid)
        return true;
    //set all the default values for the transaction
    return true;
}

Ok, I know it’s not a pillar of phenomenal code. But you get the point, both of the sides of the | are run. Now, what if you’ve all ready evaluated the status earlier in code? No need to do it again. But you may need to still set the defaults. Well, that is where the |= comes into play.

bool transStatus = VerifyStatus(Transaction.State);
//do something with the code
transStatus |= SetDefaults(Transaction);
if(transStatus)
{
    //do something with the code
}

In the case of an int a bitwise operation is performed.

int a = 0x0c;
a = a | 0x06;
//a results in 0x0000000e
//1100
//0110 results in
//1110 which is e

Like the logical operation example above the | and assignment can be collapsed down to:

int a = 0x0c;
a |= 0x06;

I think it’s very important to understand the difference between | and || as well as & and &&. Recently I came across a bunch of code where the original developer used | and || interchangeably. They are not the same. Using | in place of || overrides the fail fast nature of boolean operations most modern languages support. They are not interchangeable. If Transaction was null the following code would not work

if(Transaction == null | Transaction.State == null)

simply because both sides of the operation are evaluated so Transaction.State would throw a null pointer exception. Not only that but your code will run slower.

Next in this series will be checked and unchecked.

Later,
Brian

?? Is the way of the WORLD, HAHAHA

 Recently I gave a quick talk to the devs at the court house about the
coalesce operator. So why do you care? Well, you probably don’t so
just quit reading right now.

For those of you that are still around the coalesce operator works like
COALESCE in T-SQL.

For instance:

SELECT COALESCE(
hourly_wage * 40 * 52,
salary,
commission * num_sales) AS 'Total Salary' FROM wages

Here in T-SQL we can see a simple select statement that will determine a
person’s total salary regardless of if they are on wage, salaried or on
commission since an employee on wage would have a null salary and null
commission but an employee on salary would have a null wage and null
commission.

Basically COALESCE uses the first value it finds that doesn’t result in
a null.

So how can this help you?

Does this look familiar? (Um, I don’t really care if it looks familiar,
just keep reading. You’ve come this far.)

//set cust first name
if(cust.FirstName != null)
txtFirstName.Text = cust.Firstname;
else
txtFirstName.Text = "";

Well, with the ?? (a.k.a. coalesce operator) you can trim this down to
txtFirstName.Text = cust.FirstName ?? “”;

In T-SQL you can put an unlimited number of commas in the function to
come up with a bunch of values to check. With the ?? operator you can
just string them along, i.e.:

txtFirstName.Text = cust.FirstName ?? cust.LastName ?? cust.Nickname ?? "Name not found";

This can be taken a step further since ?? can be used with primitives.
This makes it very nice when dealing with nullable primitives.
Assuming MetaData has an Occurrence that is a int? you can get the
occurrence like:

int occurrence = MetaData.Occurrence ?? 0;

No casting just nice code.
Well, later ‘yall!

Brian

be ^ !be

 Unlike the & and | logical operators which seem to have dubious use the
^ (XOR, exclusive or) logical operator can make things quite a bit easier.

For instance ever write a IComparable?

rather then:

if (o1 == null && o2 != null)
    return false;
if (o1 != null && o2 == null)
   return false;

you can just do:
if(o1 == null ^ o2 == null)
   return false;

like the other logical operators both sides of the conditional must be
evaluated but since we’re doing exclusive or-ing here it makes sense to
do it rather then in the cases of the other logical operators where fail
fast (or short-circuiting) conditional operators (like && and ||) would
work better.