Essential C# 4.0 (3rd Edition) (Microsoft Windows Development Series)

Author: Mark Michaelis
4.0
All Stack Overflow 7

Comments

by anonymous   2017-08-20

C# 4 is basically a superset of all the other versions, so if you know C# 4 then you definitely know the earlier versions. On the other hand, I think it's worth knowing what's in which version. I have a couple of "bluffer's guides" on my C# in Depth web site which give a bit of information about C# 2 and 3 - I'll do a similar one for C# 4 soon. See this question for a very brief list of features in each version.

As for migrating from C and C++ - try to ignore everything you think you know. Some bits will be similar, some will be completely different. You should try to work the way the language expects you to, rather than applying C++ idioms to it.

You might want to read Essential C# 4.0, C# 4.0 in a Nutshell or Accelerated C# 2010. My own book - C# in Depth - will have a second edition soon, covering C# 4, but it's really designed for people who already know C# 1.

by anonymous   2017-08-20

So as Dan already mentioned, if you have a unique property you should use it as a key within a Dictionary<TKey, TValue>.

Cause checking if something is within a Dictionary is an O(1) operation, while within a List it is just O(n) in the worst case (and now imagine you have 1 million cars within your list).

var carsForSale = new Dictionary<int, Car>();

//Create a car which you like to check
var checkCar = new Car(4, Color.Red);

//Use this approach if you want to change only a few properties
//of an existing item
if (carsForSale.ContainsKey(checkCar.RegNum))
{
    carsForSale[checkCar.RegNum].Color = checkCar.Color;
}
else
{
    carsForSale[4] = checkCar;
}

//If you have to take over ALL property settings, you can also
//forget the old item and take the new one.
//The index operator is smart enough to just add a new one
//or to delete an old and add the new in one step.
carsForSale[checkCar.RegNum] = checkCar;

Dummy implementation of the car class:

public class Car
{
    public int RegNum { get; private set; }
    public Color Color { get; set; }

    public Car(int regNum)
        : this(regNum, Color.Empty)
    { }

    public Car(int regNum, Color color)
    {
        RegNum = regNum;
        Color = color;
    }
}

The problem why you are using a Dictionary is, cause you want to explicitly tell what the key is (the RegNum property of your car), but you could also use a Hashset<T> if your Car object would correctly implement Equals() and GetHashCode() but this is a little more complex than you might think. A good explanation can be found in the Essentials C# book.