Thursday 31 May 2007

Properties in C#

All good programmers have spend hours made getters and setters. So Microsoft have decided to make it a bit harder (I think now, I might change my mind later).

Heres an example of old time code

public class MyClass
{
private int x;
public int getX()
{
return x
}
}
ect.
In you application you can get x with the following code:
mc.GetX();

Now C# provides a built in mechanism called properties to do the above. In C#, properties are defined using the property declaration syntax. The general form of declaring a property is as follows.

<acces_modifier> <return_type> <property_name>
{
get { }
set { }
}

This means that I can do the top example the following way:

Where <access_modifier> can be private, public, protected or internal. The <return_type> can be any valid C# type. Note that the first part of the syntax looks quite similar to a field declaration and second part consists of a get accessor and a set accessor.

For example the above program can be modifies with a property X as follows.

class MyClass
{
private int x;
public int X // property
{
get
{ return x;}
set
{ x = value;}
}
}

The object of the class MyClass can access the property X as follows.

mc.X(10) // setter.
y = mc.X // getter.

I think its a step in a good direction, but splitting the attribute and the property is in my view, just as bad as not having them.

Wednesday 30 May 2007

equal types in vb.net and c#

Even though c# and vb.net uses the same libraries, there is some differences in what name identify the classes, below I will make a list.








vb.netc#
Booleanbool
DateSystem.DateTime
Stringstring
int32int


And keywords:







vb.netc#
Sharedstatic
Friendinternal
ReadOnly*const*



*)
const:

- Can't be static.
- Value is evaluated at compile time.
- Initiailized at declaration only.

ReadOnly:

- Can be either instance-level or static.
- Value is evaluated at run time.
- Can be initialized in declaration or by code in the constructor.

vb.net friend becomes c# internal

Porting a friendly structure from vb.net to c# is done by altering the "friend" keyword to "internal" in c#

Regions in .NET

As a fan of agile development, where everything should be structured into small classes, its hard to see regions as anything but a bad solution for a bad problem. But they are here, and people are using them, so no sense in not knowing what they do. Its a simple answer:

They do nothing, zip, nada. A region is simply a construct to enable Visual Studio.NET to hide pieces of code outside of the normal bounderies of methods, structures and classes.

In vb.net a region have the following for:
#Region "DataTypes"
' types of service:
#End Region

And in c#:

#region "DataTypes"
// types of service:
#endregion

So no magic here... Sorry

Garbage collecting in .NET

The .NET framework have automatic garbage collection, and uses an algorithm called “mark and compact” which is an variant of the “mark and sweep” algorithm, where the heap is compacted after each garbage collection. This makes the allocation very fast, since the heap is always compacted and the next free slot is just the bottom of the heap (the heap grows downwards)

Research has shown that you can split objects on the heap into two groups, the young ones which will only survive until the first garbage collection and the old ones which will stay in the heap through out the execution. The .NET garbage collector uses this by only garbage collecting the young generation each time, and the old only when its needed. [For more information read the article, or ask me]
Even though the garbage collector is automatic it doesn’t mean that you can make programs which will suffocate the GB. I the following is a list of some of the problems which can cause long GB breaks.

Performance:

• Too many allocations: Its very easy to create many temporary elements which will make the GB pause long. Don’t use f.x. String.Split, creates a new String object for each split
• Don’t make too large allocations
Its very cheap to make new allocations, and too big allocations will trigger the GB much more often, which is expensive
• Too many pointers
Structures with many pointers takes time to for the GB, because it has to run through all of them. For long lived structures this is not a problem, but if these structures will be made on a transitory basis. Even with a long lived structure can give problems, if the structure is changed over time, this can endup being distributed through out the heap and thereby make it harder for the GB to “compact” the heap
• Too many roots
Too many roots will make the mark process too long. Making deep recursive methods with many object pointers, is also a no no.
• Too many object writes.
Write to an object, and its pointers have to be checked by the GB, because the object will be registered in the card table
• Too many Almost-Long-Life objects
The biggest pitfall of them all. To avoid these kinds of objects, your best lines of defense go like this:
1. Allocate as few objects as possible, with due attention to the amount of temporary space you are using.
2. Keep the longer-lived object sizes to a minimum.
3. Keep as few object pointers on your stack as possible (those are roots).
• Use only Finalization when its necessary.
If an object is dead but has a finalizer it will be kept alive until the GB have time to run the metod body, and also all the referenced objects inside the object. Therefore use only a finalizer when its really needed. Move resources which need finalizing to a root object, to minimize the size of elements in inferno.
In many cases it is much better to implement the IDisposable interface.

To get the best out of the allocator you should consider practices such as the following:
• Allocate all of the memory (or as much as possible) to be used with a given data structure at the same time.
• Remove temporary allocations that can be avoided with little penalty in complexity.
• Minimize the number of times object pointers get written, especially those writes made to older objects.
• Reduce the density of pointers in your data structures.
• Make limited use of finalizers, and then only on "leaf" objects, as much as possible. Break objects if necessary to help with this.
Personally I think that these requirements above is a bit to restrict, because you will find other perspectives which will contradict these requirements. But I added them here as a guideline.

References:
[GB1] Mariani, Rico: Garbage Collector Basics and Performance Hints, 2003 (Link)

Structures in c#

A structure in c# is at first sight the same as a class, but there are differences, which I will describe in the following, but first the structure of the structure:


Structure:
A structure in c# has the following form:


<modifiers >
struct<struct_name>
{
//Structure members
}

or an actual example

struct Weight
{
public int
value;
public string
unit;
}


And is instantiated like this:

Weight ms = new Weight();

Unlike classes, the struct object can also be created without using the new operator.

Weight ms;

But in this case all fields of the struct will remain unassigned and the object can't be used until all of the fields are initialized.
At the bottom I have attached a larger example of a structure.


Properties of a Structure:

A structure can contain
fields, methods, constants, constructors, properties, indexers, operators and even other structure types.

It is even possible for a structure to implement a interface or inherit from another structure.

interface PhysicalUnit
{
public int getValue()
}


struct weight : PhysicalUnit
{
private int value
public int getValue(){
return value
}


The difference:
The difference between a structure and a class is the place it is put in memory. Because as we all know an object of a class type is put in the heap, with a reference (pointer
) on the stack which points to the object. An object of structure type on the other hand is placed on directly on the stack.

Example:

Below is an example of a structure which shows how a constructor, properties ect.

using
System;
struct
Complex
{
private int
x;
private int
y;
public Complex(int i, int
j)
{
x = i;
y = j;
}
public void
ShowXY()
{
Console.WriteLine("{0} {1}",x,y);
}
public static Complex operator
-(Complex c)
{
Complex temp = new
Complex();
temp.x = -c.x;
temp.y = -c.y;
return
temp;
}
}
class
MyClient
{
public static void
Main()
{
Complex c1 = new
Complex(10,20);
c1.ShowXY();
// displays 10 & 20
Complex c2 = new
Complex();
c2.ShowXY();
// displays 0 & 0
c2 = -c1;
c2.ShowXY();
// diapls -10 & -20
}
}


Operator overload
It example above also includes an example of an operator,

public
static Complex operator
-(Complex c)
{
Complex temp = new
Complex();
temp.x = -c.x;
temp.y = -c.y;
return
temp;
}


which is new to me from the Java world. but a nice feature, which should be used
carefully, since in this example its quite intuitive what happens if you take one element and subtracts it from another. But in more complex types of structures this can be more misguiding than helpful.


Tuesday 29 May 2007

Nunit in action

On my new project I am implementing a proxy, in the .NET framework. Its currently in Beta (implemented 2 years ago), and is implemented in VB6. So to be more clear I have some old VB code which should be ported, updated and tested. I vote for implementing (porting) it in C#, since I like brackets and ";" and just think its a better language than VB.NET. Anyway this blog is about how I am going to use NUnit it my new C# project (which Im starting while they are making the decision).

For info on NUnit go here (Link)

I have made a new C# project in Visual Studio 2005. which should be the actual project. In this I will add a new project to be my NUnit test project called test, which should be console application. If my new project is called "Proxy" my folder structure is as follows:
My main project: \projects\Proxy
My test project: \projects\Proxy\Test

My test project be in the same namespace as the Proxy namespace otherwise the tests wont run on private methods. You may need to add the Proxy project to the NUnit test project. so it can see the methods it should test.

Now every time I make a new method, I will make one or more test methods, to test it. And a new test class for each new class.

When I have implemented a couple of lines, I compile the testcode, and run the tests in NUnit GUI.

I just found this excellent tutorial about how to use NUnitTest in vb.net (link)

Thursday 17 May 2007

Learn your child to program

Carnegie Mellon has developed a tool called Alice, for kids and other children to learn how to use object oriented programming. The tool allows you to programming figures in a virtual 3D world. Its not rocket science, and if one need to learn programming one would probably move on quickly, but hey its fun, and introduces the concept.

Wonder how early a parent can start :)
http://www.alice.org/

In fact after looking a bit on the net, there is also other alternatives. Here is one from MIT research lab http://scratch.mit.edu/ which is a bit more complicated.

Tuesday 8 May 2007

The funny thing about SQL

I recieved a lession SQL logic the hard way, the other day.
Can you find the difference between the following two statements:
1)
select AY__ICODE, AY_UCODE, AY_SHNAM, AY_EXDES
from A_AYBOOK, A_ACTIVITY, A_MAYREQ
where MQ_IATTY = AY__ICODE
AND AK_AYCODE = AY__ICODE
and AK_BKCODE = 'IU010H01RNOL'
and MQ_IUNIT = 'SPEDA000001Y'
2)
Select count(A_ACTIVITY.AY__ICODE)
from A_AYBOOK, A_ACTIVITY, A_MAYREQ, A_SERPOIN
WHERE MQ_IATTY = AY__ICODE
and AK_AYCODE = AY__ICODE
and AK_BKCODE = 'IU010H01RNOL'
and MQ_IUNIT = 'SPEDA000001Y'
The from clause in the second statement contain a extra class A_SERPOIN. This makes the SQL return many more elements, because it interprets this as a inner join. Therefore read all your statement, before using.