Sunday, September 23, 2007

The Often Forgetful but Important Value Type

More often than not we take the little things for granted. Value types are one of the many unappreciated heroes of the .Net Framework. Value types are used on a daily basis without ever giving a second thought to performance or impact. The following post aims to characterize and explain what a value type is.

There are three categories of value types

  1. Built in types
  2. User defined types (Structures, Struct)
  3. Enumerations

General Guidelines for all value types

  • Value types contain their data directly.

  • Value types are stored in an area of memory known as the stack. The stack allows for variables to be created, read, updated and removed quickly during runtime with minimal overhead.

  • When you assign between value types the data is copied from one variable to the other. For example

    Int32 AdamsAge = 24; //Stored at memory address 1
    Int32 YourAge = age; //Stored at memory address 2

    YourAge = 30;

    AdamsAge will remain as 24.

    Thus an assignment between value types stores the data in two different areas of memory on the stack. This contrasts the behavior of reference types.

  • All value types are derived from System.ValueType.

  • All types are derived from System.Object. This means that methods may be called on value types.

  • Value types have an implicit constructor. Thus, a deceleration unwittingly instantiates the type automatically. The new keyword does not have to be included as you do with classes. The default value is usually 0 or null. As a rule of thumb you should always assign a default value.

  • As of .Net 2.0 the Nullable type is available. Nullables allow you determine if a variable has been assigned or not. A nullable type is an instance of System.Nullable. System.Nullable is a structure.

    For example boolean values may now have three states true, false, null(not selected).

    Syntax

    Nullable<bool> isVisible= null;
    bool? isVisible = null;

    A Nullable variable has the following additional properties HasValue and Value.

    For more information regarding Nullables please read the following article MSDN.


1. Built in Types

The general guidelines above apply to all built in types. Built in types are base types provided by the .Net Framework. Built in types are used to build other types. The most common types are:

  • Char
  • Boolean
  • Int32
  • Double
  • Decimal
  • DateTime
  • String Yep, that's right string is not a value type. String is in fact a reference type.

2. User Defined Types

A structure is a composite of other value types. Structures behavior is almost identical to that of a class. An example of a simple structure would be a point on a grid. The point type contains two integers X and Y. X being the horizontal location and Y being the vertical location.

The point structure could be created as follows. As you can see this point structure is very simple.

public struct Point

{

   int x;

   int y;

}

The following point structure is much more complex and offers more value. This example exposes a constructor and several methods to change the X and Y coordinates of the point.

public struct Point {

    private int x;

    private int y;

 

    public Point(int x, int y) {

        this.x = x;

        this.y = y;

    }

 

    public int X {

        get { return x; }

        set { x = value; }

    }

 

    public int Y {

        get { return y; }

        set { y = value; }

    }

 

    public void MoveUp() {

        Y += 1;

    }

 

    public void MoveDown() {

        Y -= 1;

    }

 

    public void MoveLeft() {

        X -= 1;

    }

}

Getting in the spirit of test driven development here are a few tests to illustrates how this structure works.

[TestFixture]

    public class PointTest {

        private readonly int xStartPos = 8;

        private readonly int yStartPos = 9;

        private Point point;

 

        [SetUp]

        public void SetUP() {

            point = new Point(xStartPos, yStartPos);

        }

 

        [Test]

        public void Should_Move_Down_Once() {

            point.MoveDown();

            Assert.IsTrue(point.Y == yStartPos - 1, "Should have moved the y axis down by one(Y-1).");

        }

 

        [Test]

        public void Should_Move_Down_Twice() {

            point.MoveDown();

            point.MoveDown();

            Assert.IsTrue(point.Y == yStartPos - 2, "Should have moved the y axis down by two(Y-2).");

        }

 

        [Test]

        public void Should_Move_Down_Up() {

            point.MoveUp();

            Assert.IsTrue(point.Y == yStartPos + 1, "Should have moved the Y axis up by one(Y+1).");

        }

 

        [Test]

        public void Should_Move_Left() {

            point.MoveLeft();

            Assert.IsTrue(point.X == xStartPos - 1, "Should have moved the X axis left by one(X-1).");

        }

    }

structures usually are more efficient than classes. A structure should meet the following criteria.
  • Logically represents a single value.
  • Has an instance size less than 16 bytes.
  • Will not be changed after creation.
  • Will not be cast to a reference type.

3. Enumerations

Enumerations allow you to assign values to symbols. The primary benefit of enumerations is to improve code readability. Instead of passing an arbitrary number into a method one can pass in a meaningful symbol. The following is an example of an enumeration.

 

public enum CarManufacturers { Honda, Acura, BWM, Audi, Mazda, Hyundai, GM }

 

public class Car {

    private CarManufacturers manufacturer;

    public Car(CarManufacturers manufacturer) {

        this.manufacturer = manufacturer;

    }

 

    public CarManufacturers Manufacturer {

        get { return manufacturer; }

    }

}

 

//We can now easily check the manufacturer of a car

 Car car = new Car(CarManufacturers.Honda);

 

 if(car.Manufacturer.Equals(CarManufacturers.Honda))

    Console.Write("Honda");

 

2 comments:

Anonymous said...

Who knows where to download XRumer 5.0 Palladium?
Help, please. All recommend this program to effectively advertise on the Internet, this is the best program!

marko said...

There are better places that you can go to apply for home advances and frequently, your bank is your most solid option since they offer the least premium. The issue is that their desires are very high and many individuals can't meet the capability guidelines that are set by the banks. check cashing