Thursday, February 14, 2008

C# keywords: readonly vs const

The readonly keyword is different from the const keyword. A const field can only be initialized at the declaration of the field. A readonly field can be initialized either at the declaration or in a constructor. Therefore, readonly fields can have different values depending on the constructor used.

In a nut shell we can say that, while a const field is a compile-time constant, the readonly field can be used for runtime constants as in the following example:

public static readonly uint l1 = (uint) DateTime.Now.Ticks;

Refrences: MSDN July 2004

namaste !

Thursday, February 7, 2008

ByRef keyword while passing arguments in C#

I have to come up with this post when I heard a number of people saying that “all Reference type values in C# are passed ‘By Reference’ and the byRef Keyword is there just to increase the readability of code”

So my dear friend this is not the case at all byRef Keyword is not here to increase the readability of code!

So what does byRef actually do?

In situations when we have to pass a Reference Type argument and there is a need to use new operator on the passed argument; we have to have make use of byRef keyword otherwise a new dangling instance will be created on the HEAP (as reference types are stored on heap).

By dangling instance I mean that the newly created memory location will not be linked to the variable for which we called new operator.
You will not get any compile time or runtime error but the code will behave as if you never used the new operator.

I guess we can better understand this with the help of a simple example. So please go ahead and experience it!

You are welcome to leave comments so that I can help you out if more clarification is required.

namaste!  Atreya, A