Thought for the Dazed

I've had to give up that Distance Learning course as I was having trouble seeing the teacher.

Flickr
www.flickr.com
RobMiles' items Go to RobMiles' photostream
Twitter
C# Yellow Book

Search entire site

Entries by Rob (3094)

Thursday
Aug292013

What does ?? mean in C#

WP_20130829_17_11_38_Pro__highres.jpg

I sent out a tweet asking folks if they knew what the ?? operator in C# does. Quite a few people did, which was nice. For those of you that haven’t heard of it, here is my explanation.

If you are a C# programmer you will know about references. The way that C# works, a variable can be managed by value or reference. A variable of value type is stored in a location in memory. For example:

int i;

This creates an integer variable called i. When the program runs the system will decide where in memory the variable should live. You can think of computer memory as a whole bunch of numbered locations. Because that is what it is. Perhaps the variable i could live at memory location 5,000. Then when we write the code:

i=99;

The effect of this is to put the value 99 in memory location number 5,000

So, if I write code like:

j = i;

This would copy the value held in memory location 5,000 into the location where the integer variable j is stored.

This is how value types work. Whenever we do an assignment of a variable managed by value what happens is that the value is copied from one memory location to another.

So, what about values managed by reference? Well, in these there is a level of indirection between the variable and the actual data. Suppose we have a class called Account, which is managed by reference.

Account a = new Account();

This statement makes a new account variable and then sets the variable a to refer to it. The variable a will hold a reference to the new Account. Perhaps the new Account will be located at memory location 10,000 which means that the variable a (which might be stored at location 6,000) will hold the number 10,000 – because that is where the Account instance is stored. The Account class might have a Name property, so I can write code like:

a.Name = "Rob";

When the program runs it will go to location 6,000 (where a is stored) and read the number out of there to find out where the Account is. In this case the variable a holds the number 10,000 and so the program will go to the Account there and set the name.

So if write code such as:

Account b = a;

This creates a new Account reference called b which refers to the same Account instance as a, in other words it will refer to location 10,000.

So, in the case of the value the information is just there in memory, but for a reference we have to go where the reference refers. With references you can also set them to null:

a = null;

This has the effect of putting a “magic value” in the variable a that indicates it really points nowhere.  It is a way of saying “this reference does not point to any object”.

The null reference is often used in programs to indicate that the thing you asked for could not be found, or hasn’t been made yet, or doesn’t matter.

This “nullability” is so useful that people wanted to be able to make values “null” as well. So they invented one.

int? ageValue;
The addition of the question mark makes an integer variable (ageValue) that can be made null. For example, the bank might store the age of a customer when it is important (when the age is less than 20 say) but once a person reaches a certain age, from then on the age is completely irrelevant to the system. They can mark the ageValue as null to indicate this.

ageValue = null;

Programs can also test for null

if (customerAge != null)
{
// Stuff you do if the age matters
}

In XNA you often find nullable value parameters being sent to method, so that the method can know to ignore them.

So, I’ve been writing for what seems like ages, and I’ve still not explained what ?? does.

Well, ?? provides a convenient way that I can map the null value of a nullable variable onto a specific value

int actualAge = customerAge ?? -1;

It saves us having to write code that tests for null and sets a value appropriately. The above statement sets the value of actualAge to the value in customerAge unless the value in customerAge is null, in which case it sets it to –1.

if (customerAge == null)
actualAge = -1;
else
actualAge = customerAge;

In other words ?? is a short form of the above test.

Wednesday
Aug282013

Feminine Logic

WP_20130827_17_04_42_Pro.jpg

Last week our washing machine broke. Yesterday I fitted the new one. Only problem is that the new machine is slightly larger and catches a cupboard door so that it won’t quite open as wide as it used to. This means that we can’t get the cleaning bucket out of the cupboard very easily. My proposed solution was to design and 3D print a new hinge that moved the door pivot point as it was opened so that it didn’t catch the washing machine and the door could open further. Number one wife suggested we put the bucket in another cupboard.

Tuesday
Aug272013

You really should go to “Your Really Should” events at C4DI

WP_20130827_18_14_46_Pro__highres.jpg

Simon Hudson (left) and Jon Moss, with a Lumia 1020 in the middle..

I seem to be spending  a fair bit of time at C4DI at the moment. Tonight I was there for the first of their “You really should be..” events. The format is simple enough. Take the words “Your really should be..” and put them in front of something that you can talk about for fifteen minutes. Then take questions and repeat twice. It works really well, generating discussion and interesting things to do in equal measure. And the first topic was right up my street, when Simon Hudson spoke on “You Really Should Be giving a Windows phone a try”. Absolutely.

Simon gave a great description of what makes Windows Phone is such a nice platform, starting with some impressive sales figures (now phone platform number three) and moving on to the neat and useful things you can do with the device. Of course, I don’t need convincing of any of this, but it was lovely to hear someone else voice the same opinions and give some strong context about how Windows Phone is proving so useful to them. Highlights were Voice SMS, Live Tiles and Rooms. You can find Simon’s presentation here. For me the killer fact was that his daughter was into Windows Phone first and he got his after her.

Next up was David Gilson: “You Really Should Be buying Bitcoins!”. Bitcoins are “maths made money” in that the actual currency is created as a series of mathematical proofs, each of which identifies a particular coin. Coins are mined by computers that grind through calculations to generate the proofs which are assigned to owners.

When you buy a bitcoin or use part of it to pay for something the transaction is stored as part of the bitcoin infrastructure in a series of tamperproof blocks. You can use bitcoins to pay for stuff and you can buy them and keep them in your digital wallet. There are 21Million possible Bitcoins out there, and they will get both harder to mine and more valuable over time. At the moment around half the Bitcoins have been “mined” and people are investing in ever more powerful systems to find more. The idea is to do away with the present volatile paper based currency systems and replace them with something clean and mathematically sound.

As you might expect, the world of finance is looking a little askance at this attempt to make an end run around the systems that have made, and are keeping them rich. Bitcoins, with their untraceable ownership and easy electronic transfer, are also also ripe for use by various unsavoury enterprises. Me, I’ll be keeping my cash in traditional forms for the time being, but David did make a very compelling case for “having a flutter” on Bitcoins.

Finally Jon Moss rounded off a very enjoyable evening with a session called “You Really Should Be using Textexpander”. The TextExpander program installs on your Mac and allows you to create and manage keyboard shortcuts to vastly improve your speed when creating documents. Rather than typing “From the pen of the desk of Rob Miles” at the end of each email I could assign that to ESIG or some other combination of letters and numbers. TextExpander monitors your keyboard and then inserts the expanded version when it sees the shortcut.

That’s nice enough, but there is a lot more besides. You can create template documents, for example meeting minutes or email responses and have them all created automagically. If you find yourself typing the same phrase, or building the same document, time after time then this system would save you a lot of work.

It is a pity that the program is only available on Mac (although it is available across all the Apple platforms and works really well on iPhone and iPad). If you fancy having a go at this and are using a Windows PC Jon reckoned that PhraseExpress is your best bet.

It was an absolutely great evening. And when I went out of the office I was able to grab a nice picture of The Deep again.

WP_20130827_19_30_41_Pro__highres.jpg

C4DI have set up a web site:

http://www.youreallyshouldbe.com/

You really should be keeping an eye on it.

Monday
Aug262013

Updating Display Elements in Windows Phone

WP_20130820_16_20_32_Pro.jpg

This is another in my series of “put this in the blog so that you don’t forget it” posts.

Everyone (or nearly everyone) knows that you can update elements on a Windows Phone display by setting properties on them:

statusTextBlock.Text = "Hello Rob";

This would display “Hello Rob” on the phone screen. The snag is that only code that is running in the context of the page can do this. In other words, I can change the display when page events occur, for example buttons being pressed, but I can’t change the content of the TextBlock in response to a network message arriving because the network message code is not running in the same context of the display page. If I try to do this the program fails at runtime with an exception.

The way to fix this is to use a “dispatcher”. The dispatcher is part of the display management system and it will run things in the context of the display system for you. So, you have to give the dispatcher the thing you want to have done, and it will do it on your behalf. This is a bit like you sending one of your kids to go and buy you some Disney Infinity figures because you are to embarrassed to go yourself. Rather than do the task, you hand it off to another process to have it performed for you.

The best way to do this is to use a “lambda expression”. I hate this name. It makes the expression sound all clever and mathematical, when actually it is really just a useful trick that lets you treat executable code as a lump of data that you can give to something else. What you do is use a the “lamda expression” to wrap you your update behaviour and then pass the result of this expression into the method. In fact it all works with delegates, but to make simple use of the feature you don’t need to know this.

statusTextBlock.Dispatcher.BeginInvoke(() =>
{
    statusTextBlock.Text = "Hello Rob";
});

The Dispatcher object is the member of the XAML component that will run the method for us. All XAML display elements have a Dispatcher and it exposes a method called BeginInvoke that will run our code. The parameter to BeginInvoke is the code we want to have run, and this is where the Lamda magic starts.

statusTextBlock.Dispatcher.BeginInvoke(() =>
{
    statusTextBlock.Text = "Hello Rob";
});

I've highlighted the actual lamdba expression in the code sample above. It is everything between the ( and ) that goes into the BeginInvoke method. If we pull it out of there we can get a closer look.

() =>
{
    statusTextBlock.Text = "Hello Rob";
}

The item at the top, the () part, means that the code in this lambda expression does not act on any data. If you want to pass parameters into the code inside the lambda expression you can do this, but we don’t need to.

The => sequence is the lambda itself, and it is followed by the block of statements that are obeyed. If we were buying Disney Infinity figures this would be where I put the behaviour to ask for a “Mrs Incredible”. What actually happens is that the lump of code is stashed somewhere and a delegate (which in C# is how we manage pointers to code) is created to pass into the method.

So, when my program runs the BeginInvoke method in the Dispatcher is given a lump of code to run. It adds this lump of code to a list of “things to do” next time it has to update the display. This means that the display doesn’t actually update precisely when you ask it to, but the process happens so quickly that this is not a problem.

Sunday
Aug252013

Powertache Game

image

Ever fancied playing a card game with the aim of finding the most powerful moustache? Well, if you do, thanks to number one daughter, I’ve got a copy. It is a bit like Geek Power, but based on facial hair. The pictures are great (where do they find these people?), along with the captions.