Archive

Archive for June, 2007

Reference & Value types - Pass by Value, Pass by Reference (.NET)

June 28th, 2007

A colleague of mine is learning C# and was asking me some questions about the difference between Reference and Value types in C#. We then went on to discuss the different semantics of passing Reference and Value types by reference or by value.

Firstly a few definitions

  • Value Type = Any structure (struct in C#), all of the primitive types eg. int, double, DateTime etc (not including string).
  • Reference Type = Anything inheriting from object, this means anything defined as a class.
  • Pointer = The location of a reference type (which is what you have when you have a Reference Type variable)
  • Mutable = If an object is mutable it’s internal state can be changed byt calling methods and/or properties, for example neither String nor DateTime are mutable since any method/property that would change state returns a new String or DateTime.

There are a number of seperate cases you need to consider, I’m going to create a Swapper class to demonstrate.

using System;public static class Swapper

{

 [STAThread]

 static void Main()

 {

  SwapperTests();

 }public static void SwapperTests()

 {

  object leftRef = "left";

  object rightRef = "right";

  int leftIntVal = 1;

  int rightIntVal = 2;

  double leftDoubleVal = 1;

  double rightDoubleVal = 2;  Swap(leftRef, rightRef); // Passing Reference Types By Value

  Swap(ref leftRef, ref rightRef); // Passing Reference Types By Reference  Swap(leftIntVal, rightIntVal); // Passing Value Types By Value

  Swap(ref leftIntVal, ref rightIntVal); // Passing Value Types By Reference  SwapGeneric(leftDoubleVal, rightDoubleVal); // Passing Value Types By Value (boxed)

  SwapGeneric(ref leftDoubleVal, ref rightDoubleVal); // Passing Value Types By Reference (boxed)

 }public static void Swap(object left, object right)

 {

  object temp = left;

  left = right;

  right = temp;

 }public static void Swap(ref object left, ref object right)

 {

  object temp = left;

  left = right;

  right = temp;

 }public static void Swap(int left, int right)

 {

  int temp = left;

  left = right;

  right = temp;

 }public static void Swap(ref int left, ref int right)

 {

  int temp = left;

  left = right;

  right = temp;

 }public static void SwapGeneric(T left, T right)

 {

  T temp = left;

  left = right;

  right = temp;

 }public static void SwapGeneric(ref T left, ref T right)

 {

  T temp = left;

  left = right;

  right = temp;

 }

}

Taking each of these in turn there are 2 things to consider

  • Will the swap work as expected?
  • If the parameters are mutable will changes be reflected outside of the method
  • Swap(leftRef, rightRef); // Passing Reference Types By Value
    1. No, when the Swap method is called the runtime creates two new reference types (left and right) and sets them to the same address as leftRef and rightRef, when the swap is carried out only the local references are changed (so left now points to “right” and right points to “left” but leftRef and rightRef are unchanged).
    2. Yes, this could catch you out! Since left and right are both valid pointers to objects any mutable objects could be changed by the method and the changes WOULD be seen in the calling method.
  • Swap(ref leftRef, ref rightRef); // Passing Reference Types By Reference
    1. Yes, this is in fact the correct way to define this method, leftRef and rightRef are passed into the Swap method so they can be changed, no copies are made!
    2. Yes, again as long as you have a pointer to a mutable object you can change it’s state.
  • Swap(leftIntVal, rightIntVal); // Passing Value Types By Value
    1. No, similarly to the object version this won’t work. Two new ints are created and passed into Swap. This means you are onhly working on copies of leftIntVal and rightIntVal so the changes are not seen outside the method
    2. No, this is different to how objects behave, with objects only the pointer is copied but with value types all the data is copied so NO changes are seen outside the method.
  • Swap(ref leftIntVal, ref rightIntVal); // Passing Value Types By Reference
    1. Yes, in this case the actual leftIntVal and leftIntVal variables are passed into the swap function so any changes are seen outside
    2. Yes, in this case the actual leftIntVal and leftIntVal variables are passed into the swap function so any changes are seen outside

In .NET v2.0 you would define the two methods as shown in SwapGeneric, these methods will correctly infer the types of variable being passed in and will behave as described above depending on what is passed in.

Or pictorially

By Ref, By Val

/Technology

The days are getting shorter

June 27th, 2007

Well June 21st has been and gone so the days are getting shorter, this means I’m officially allowed to start thinking about snowy pursuits again! I’ve decided on my 5 missions for this season

  1. Take my CASI Level 1 (and ideally pass it)
  2. Learn more about avalanches (Whistler run some Free Avalanche Awareness Tours but this seems a minimum)
  3. Go on a (guided?) backcountry adventure (WhistlerGuides), need to do some research here
  4. Nail a 360 (freestyle still isn’t really my thing)
  5. Ride as much as possible in as many resorts as possible

/Snowboarding

Facebook

June 27th, 2007

I resisted for ages but recently John succumbed closely followed by Ruth so I figured I’d take a look and see what everyone was talking about. It turns out it’s frighteningly addictive, I have 59 friends (largely ex-colleagues) , I’ve persuaded several other people to join (sorry guys) and got back in contact with a few people I’d lost touch with. It’s actually a really good way to keep in touch with people. It’s similar to LinkedIn  and Friends Reunited (both of which I’ve been a member of for a while) but without the charges to send messages to people. Anyway if you know me, add me as a friend

/Technology ,

Blog Disaster

June 27th, 2007

As you’ve probably noticed (or not since I always read blogs via rss and you probably do too) I recently stuffed up our blog, now this isn’t that uncommon (I like to fiddle with things and often end up breaking them) however this time I really messed something up and couldn’t persuade pebble to work. Now mainly this is because Tomcat, JSP and me are things that rarely mix so I decided it was time to switch to a blog platform I had half a clue how to support (and change for that matter).

Anyway we’ve switched to WordPress which was remarkably easy to install and configure, finding a nice theme was probably the hardest part (I’m still fiddling with it but it’s pretty close). It actually feels slower than Pebble which is a testament to Simon’s coding prowess since Tomcat isn’t exactly a lightweight application. I’m hoping the wp-cache plugin will mitigate this somewhat.

There are certainly a few broken links around (missing images mainly) and probably some duff deep links floating about on the web (mod_rewrite to the rescue!), I’ve found a few already and redirected the rss feeds to their new location. I need to decide what to do about the root rss feed since WordPress doesn’t handle multiple blogs as nicely as Pebble. I might knock up a snippet of PHP to amalgamate the three rss feeds into one if I get time. I  also need to replace the old Pebble frontpage with something sensible.

Migrating content was pretty simple, Wordpress has an extended version of RSS which it will import and Pebble helpfully stores everything in XML so I knocked up a quick C# app to convert all my Pebble entries into Wordpress ones. I’ve attached the code so you can take a look. It’s pretty simple but may come in handy for someone else one day. It’s only tested on my data so it may not work well for everybody!

Pebble XML to Wordpress RSS

/Technology

Vista: Less vulnerabilites than RedHat, Ubuntu, MAC OS X 10.4

June 22nd, 2007

Before the Mac and Linux fanboys jump all over this (as they have in several other blogs who have mentioned this report). I’ll point out upfront the following:

  • Yes, the guy who wrote the report works for Microsoft
  • No, this doesn’t (necessarily) mean he is biased
  • I use Linux (several flavours), Unix and Windows both at work and at home so I’m not biased either (although Macs suck of course, just checking to see if Simon still reads my blog :))

The Vista 6 month vulnerabilty report shows that Vista had less security bugs than XP, RHEL4 Workstation, Ubuntu 6.06 LTS, Novell SLED10 and Mac OS X 10.4. The report is based mainly on data available in the National Vulnerability Database so if I decided to compile this report I’d get similar figures (disclosed but unfixed problems being harder to track due to the number of places problems are disclosed).

There is a long held (much promoted) belief that using Linux or Mac OS X makes you immune to viruses etc. and similarly the fallacious belief that using FireFox or Safari makes you immune to any internet badness. This was (perhaps) ever so briefly true because the bad guys (people who want to ‘own’ your computer) logically focused on Windows due to it’s huge user base and the good guys (security researchers etc) did the same for similar reasons. This (combined with the let’s bash MS because it’s cool movement) started the whole “Use Linux/Safari… because it’s more secure” movement. The movement has largely been successful, more and more people are using Macs (although I think the ‘iPod effect’ has had a lot to do with that) and Linux is becoming much more popular and starting to look viable as a desktop system for the masses.

To my mind this ‘movement’ is starting to have exactly the opposite effect. The scrutiny MS is under and the intense bashing they have had from not focusing on security has placed them under immense evolutionary pressure. There is an arms race running between the bad guys, the good guys and the Microsoft. The bad guys have got more and more sophisticated in there attacks the security researchers have developed better and better tools to find bugs in Windows, Microsoft have their Trusted Computing Group to improve code security. The net result of all of this is Windows has got much more secure (as shown by the recent Vista release).

On the other side of the table the increased user base of Linux, OS X, Safari etc is making them attractive targets to both the bad guys and the good guys so more and more vulnerabilities are being found in products that were traditionally believed to be more secure than their MS equivalents. Obviously MS have a huge marketing problem to solve since they are still widely believed to be the producers of shoddy insecure software. Looking at Slashdot I think it’s going to be a whole generation before they get over this hurdle.

To conclude, I really hope that the end of all this is more secure software for all of us. Software is complex and (arguably) the most difficult area of engineering today. Once you add the interactions between different packages and the OS there are (amost literally) an infinite number of ways things can go wrong. With the current state of software engineering it is impossible to eliminate all the bugs and even if you had managed it you’d never know.

/Technology ,

You know you live in Vancouver when…

June 19th, 2007

Many of these ring true…

  • You feel guilty throwing aluminum cans or paper in the trash
  • You see two Starbucks locations directly across the street from each other and think nothing of it
  • You use the statement “sunny break” and know what it means.
  • You know more than 10 ways to order coffee.
  • You feel overdressed wearing a suit to a nice restaurant.
  • You stand on a deserted corner in the rain waiting for the “Walk” signal.
  • You consider that if it has no snow, it is not a real mountain.
  • You can taste the difference between Starbucks, Blenz, and Tim Horton’s.
  • Your concept of a city’s downtown core does not include freeways.
  • Living downtown and working in the suburbs does not seem like a strange idea.
  • You’ve seen enough bus drivers re-mount bus poles to overhead trolley wires that you think you could do it yourself.
  • You know the difference between Chinook, Coho, and Sockeye salmon.
  • You know how to pronounce Squamish, Osoyoos, Coquitlam,
    Nanaimo,Chilliwack, and Tsawwassen (although you might argue about the last one).
  • You consider swimming an indoor sport.
  • You can tell the difference between Japanese, Chinese,
    Vietnamese,Korean, and Thai food as well as the languages, even if you don’t speak them.
  • In winter, you go to work in the dark and come home in the dark while only working eight-hour days.
  • You never go camping without waterproof matches and a poncho.
  • You are not fazed by “Today’s forecast: showers followed by rain,”and “Tomorrow’s forecast: rain followed by showers.”
  • You cannot wait for a day with “showers and sunny breaks.”
  • You have no concept of humidity without precipitation.
  • You know that Dawson Creek is a town, not a TV show.
  • You can point to at least two ski mountains, even if you cannot see through the cloud cover.
  • You notice “the mountains are out” when it is a pretty day and you can actually see them.
  • You’re comfortable living within sight of a 10,000-foot
    glacier-clad volcano that could become active at any time˜and you know that its being in another country will be no help if it does. (but the wind will blow ash mostly east … eh?)
  • You put on your shorts when the temperature gets above 5, but still wear your hiking boots and parka.
  • You switch to your sandals when it gets about 10, but keep your socks on.
  • You have actually used your mountain bike on a mountain.
  • You think people who use umbrellas are either wimps, tourists, or smart locals who use them for sun protection in the summer.
  • You recognize the background shots in your favourite movies and TV shows.
  • You buy new sunglasses every year, because you can’t find the old ones after such a long time.
  • You measure distance in hours.
  • You often switch from “heat” to “a/c” in your car in the same day.
  • You use a down comforter in the summer.
  • You carry jumper cables in your car and your spouse knows how to use them.
  • You design your kid’s Halloween costume to fit under a raincoat.
  • You know all the important seasons: Almost Winter, Winter, Still Raining (Spring), Road Construction (Summer), and Raining Again (Autumn).
  • You are aware that “curry” is not a spice, but a combination of spices.

Uncategorized

Yahoo: Slurp

June 15th, 2007

Just checked my weblogs and found out Yahoo Slurp has used over 13GB of my precious bandwidth (compared to 2GB for the whole of May) this month, the next closest is GoogleBot at around 1GB. Needless to say I’m not very impressed so I’m going to block them until their bot learns to behave. Grrrr

/Technology ,