Archive

Archive for December, 2008

C# .Net Tutorial 1: Value Types

December 26, 2008 scerrimark 1 comment

Value types are the simplest type in the .NET Framework. Value types are variables that contain data not a reference to data stored somewhere else. The data stored in value types are kept in the stack. The .NET Framework has 3 general value types:

  • Built-in types,
  • User-defined types, and
  • Enumerations.

All these types are derived from the System.Value base type in .NET. Let’s start by looking at the built-in types.

Built-In Value Types

Built-in types can be used to built other types. The following is a list of all the numeric built-in types in .NET:

  • sbyte – 1 byte; stores values from -128 to 127.
  • byte – 1 byte; stores values from 0 to 255.
  • short – 2 bytes; stores values from -32768 to 32767.
  • int – 4 bytes; stores values from -2147483648 to 2147483647.
  • uint – 4 bytes; stores values from 0 to 4294967295.
  • long – 8 bytes; stores values from -9223372036854775808 to 9223372036854775807 (half my monthly salary :) ).
  • float – 4 bytes; stores values from -3.402823E+38 to 3.402823E+38.
  • double – 8 bytes; stores values from -1.79769313486232E+308 to 1.79769313486232E+308.
  • decimal – 16 bytes; stores values from -79228162514264337593543950335 to 79228162514264337593543950335 (whew!!).

Note: The last three types are used for floating point operations. For optimal performance, the runtime optimizes the performance of int and uint. For floating point operations double is the most efficient because it is optimized by hardware.

The other non-numeric types are the following:

  • char – 2 bytes; stores single unicode characters.
  • bool – 4 bytes; stores True/False values.
  • DateTime – 8 bytes; stores a moment in time.
  • IntPtr – size is platform dependent; contains a pointer to memory.

When you assign one value type variable to another, the values are stored in two different locations on the stack.

It is important to note that value-types can still function like objects. For example each value-type has a method ToString that is used to represent the value of a variable in string type. This method is overridden from the System.Object type (why? Simple! All types are derived from System.Object).

How to Declare Value types

To declare value types you use the following syntax:

type name;     or     type name = value;

For example:

bool isAdult; or int num = 15;

In the first example we are just declaring a variable, while in the second example we are declaring a variable and assigning a value. If a value is not assigned the constructor of the value-type will assign a default value (normally null or 0). It is recommended that you always initialize variables when you declare them. Also note that C# unlike Visual Basic is case sensitive therefore these two variables are not the same variable:

char letter = ‘a’; is not the same as    char Letter = ‘a’;

You can declare a variable to be null ( or nullable) if you want to determine whether a value has not been assigned.  The following example shows how to declare a nullable Boolean variable:

Nullable<bool> b = null;

A short hand notation exists for C#:

bool? b = null;

The Nullable type has been introduced in .NET Framework 2.0. But you may ask what will achieve through this? When you declare a Nullable variable, the variable will have two additional members. These are HasValue and Value members. The following piece of code will help you understand better:

if (b.HasValue)
    Console.WriteLine("b has a value of {0}",b.Value);
else
    Console.WriteLine("b is not set");

Don’t worry if you did not understand all the code. But what we are doing here is to check if b has a value or  not (using the HasValue member). If it has it will print the value on screen. If it does not have then it will print the following message: b is not set.

Creating User-defined Types

User-defined types are called structures or structs. Structures are made up of other value-types. Structures make it easier to work with related data. For example a structure in .NET is the System.Drawing.Point which contains two integers for the x and y coordinates. Working with this structure is relatively easy as shown in the following code:

System.Drawing.Point pt = new System.Drawing.Point(1,3);  //assigning the x and y coordinates through the System.Drawing.Point constructor (that is why there is the new keyword)

pt.offset(2,2); //moves the point
Console.WriteLine("New point is ({0},{1})", pt.X, pt.Y); //displays the new point on screen

To create your own structure you use the struct keyword in C#. Here comes an example of a strange struct called StrangeInt. This struct stores an integer. But when you add two StrangeInt variables it will return double the sum and if you subtract two StrangeInt variables it will return half the difference:

struct StrangeInt
{
    int _val; //private members

    //Constructor
    public StrangeInt(int value)
    {
        this._val = value;
    }

    public int Value
    {
        get { return this._val; }
    }

    public override string ToString()
    {
        return Value.ToString();
    }

    public static StrangeInt operator +(StrangeInt arg1, StrangeInt arg2)
    {
        int temp = arg1.Value + arg2.Value;
        return new StrangeInt(temp * 2);
    }

    public static StrangeInt operator -(StrangeInt arg1, StrangeInt arg2)
    {
        int temp = arg1.Value - arg2.Value;
        return new StrangeInt(temp/2);
    }
}

The Operator keyword is new in .NET 2.0 and is used to determine the (new/unusual) behaviour of operators (+, – ,*, /). Here is an example of how the  StrangeInt structure will be used:

StrangeInt s1 = new StrangeInt(20);
StrangeInt s2 = new StrangeInt(15);

StrangeInt sum = s1 + s2;
StrangeInt difference = s1 - s2;

Console.WriteLine("The sum of {0} and {1} is {2}",s1.ToString(), s2.ToString(), sum.ToString());
Console.WriteLine("The difference of {0} and {1} is {2}",s1.ToString(), s2.ToString(), difference.ToString());

This code will give a sum of 70 (20 + 15 = 35 * 2 = 70) and a difference of 2 (20 – 15 = 5 / 2 = 2 in non floating point representation).

This struct can be easily changed into a class. If this change is made the variables will be stored on heap. This will be covered in the next tutorial.

So when are we to use structures instead of classes? Structures are more efficient than classes and these should be used when:

  • Logically it represents a single value,
  • Will not be changed after it is created, and it
  • Will not be cast to a reference type.

How to create Enumerations

Enumerations are symbols that have fixed values. These are created mainly to improve code readability by using meaningful symbols. An example will help more:

enum Days : int {Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday};

Days dayToday = Days.Friday;
Console.WriteLine("Today is {0}", dayToday); //displays Friday

Ok I think it is enough for today. Hope you liked my first tutorial. Please leave comments to tell me if you liked it, what you want to improve, and if you have any queries.

Until then stay tuned for the next tutorial: Reference types. CU

Categories: C# .NET

C# .NET Tutorial: Introduction

December 24, 2008 scerrimark 2 comments

As I promised in my first post I will start uploading a series of C# tutorials for those of you who want to dirty their hands in this fabulous language. In this introductory post I will explain how I will divide this series of tutorials. But before I do that I will tell you what you will gain after reading this series of tutorials.

After you have finished this series of tutorials you will be able to create .NET applications that:

  • use system types and collections,
  • implement multi-threading,
  • use classes that can be serialized so that they can be easily stored and transferred,
  • are able to communicate with other applications (even applications written in old languages),
  • are able to send e-mail messages,
  • are secure,
  • are multilingual and can be used in different languages, and finally
  • contain multimedia such as videos, images, charts and the rest.

It is very important to note that in this series of tutorials I am assuming that you have some knowledge (not a lot) in application development using any object-oriented language (preferably C# or Visual Basic), and that you have some basic knowledge of how Microsoft Windows works. It would be great if you go over the basic syntax of C# (nothing complex).

Before you can start this series of tutorials make sure that you have the following software requirments:

  • Operating System (any of the following): Windows 2000 with Service Pack 4, Windows XP Service Pack 2, Windows XP x64, Windows Server 2003 Service Pack 1, Windows Server 2003 x64, Windows Server 2003 R2, or Windows Vista.
  • Additional Software: Microsoft Visual C# Express Edition, which you can get from here.

In the first 4 tutorials we will be going through the .NET fundamentals mainly using value and reference types, constructing classes, and converting between types.

So it looks exciting doesn’t it? Well stay tuned for the first tutorial that I will upload in the coming days. By that time if you have any comments or any queries just leave a comment. CU soon!!!

Categories: C# .NET

Welcome to the eye on the web

December 23, 2008 scerrimark 1 comment

Hello and welcome to my blog! I am a software developer (well more web than software) and I set up this blog to share with you experiences that I encounter everyday whilst developing.

The web has become quite a beast today and technologies are surfacing everyday. This is the aim of the blog. We developers can share together knowledge in different technologies. A number of categories have been set up for this blog. However in the future I plan to add to these categories (who knows what I will use next).

To start with I will be uploading a series of tutorials I have written on C#. These tutorials start with the very basic of C# .NET and cover the foundations of C# So those who want to get their hands dirty with .NET definitely stay tuned :P .

The future looks bright!!!

Categories: Blog