Optimizing associative operations

A question I occasionally get is, suppose I have code like this:

const double x = 200.0;
const double y = 0.5;
...
void M(double z)
{
  double r = z * x * y;
  ...

Does the compiler generate code as though you’d written z * 100.0?
Continue reading

Advertisements

Inferring from “is”, part two

In part one I gave a bunch of reasons to reject the proposed feature where the compiler infers additional type information about a local variable when inside the consequence of a conditional statement:

if (animal is Dog)
{
    animal.Bark(); 
    // instead of ((Dog)animal).Bark();
}

But the problem still remains that this is a fairly common pattern, and that it seems weird that the compiler cannot make the necessary inference.

A number of readers anticipated my denouement and made some of the same proposals I was going to make in this part. Let’s go through a few of them; see the comments to the previous article for a few more.

Continue reading

It’s still essential

I am excited to announce that Essential C# 6.0 is now available in stores!

As always, Mark did the vast majority of the work. And as always, I was delighted to be asked once again to contribute to one of my favourite C# books. The title is well-chosen; it really does give the essentials.

Mark and I are both cyclists (though he is in a lot better shape than I am!) and so I also love that every edition has gotten more and more bicycle on the cover:

2cover

3cover

4cover

5cover

6cover

Inferring from “is”, part one

In last week’s episode of FAIC I was discussing code of the form:

if (animal is Dog)
    ((Dog)animal).Bark();

Specifically, why the cast was illegal if the variable tested was of generic parameter type. Today I want to take a bit of a different tack and examine the question “why do we need to insert a cast at all?” After all, the compiler should know that within the consequence of the if, the variable animal is guaranteed to be of type Dog. (And is guaranteed to be non-null!) Shouldn’t the code simply be:

if (animal is Dog)
    animal.Bark();

Continue reading

Casts and type parameters do not mix

Here’s a question I’m asked occasionally:

void M<T>(T t) where T : Animal
{
  // This gives a compile-time error:
  if (t is Dog)
    ((Dog)t).Bark(); 
  // But this does not:
  if (t is Dog)
    (t as Dog).Bark();
}

What’s going on here? Why is the cast operator rejected? The reason illustrates yet again that the cast operator is super weird.
Continue reading