Freelance Writing Jobs | Today's Articles | Sign In

 
Browse Sections

Pointers in C#


C# is a strongly typed programming language. Programmers who have experience with other programming languages, such as C/C++ or Cobol (yes, many are still around), will find that C# is too strict and may give the impression that the language is limiting their problem solving abilities and programming style. There is a purpose for all this and if you think more about it, the more you will accept that C#'s type system is not really bad.

A goal of Microsoft's .Net platform is to achieve greater software interoperability. A component written in Perl (Perl.Net) can be easily used in Visual Basic (VB.Net) and C++. Of course, C# can just as easily use components written in other languages. Having a common type system is therefore one of the challenges Microsoft had to deal with when designing C# and the .Net platform.

To compound the issue of having a common type system, Microsoft also had to make sure that the new platform does not deviate too much. The reason for this is cost. If Microsoft introduces too much change it will guarantee failure because companies and developers will not adopt the new technology early. The cost of moving existing applications to a new untested platform is too risky and costly.

Productivity is high when using C# because the programmer is more focused in solving the problem at hand rather than solving technical limitations of a programming language.

Let us take the following C example.

Listing 1
#include <stdio.h>

void CallFunction(int *);

void main()
{
int counter = 0;
CallFunction( &counter );
printf("Counter is: %d\n", counter);
}

void CallFunction( int *counter )
{
*counter = 10;
}

The objective of this example is to pass the variable counter and modify its contents within the called function. To achieve the same in C#, you might write your program similar to Listing 2.


By adding the ref keyword in front of the parameter, we tell C# that the parameter is to be treated as a reference. Therefore instead of passing a value, C# passes a reference to the variable. This achieves the same effect as passing a pointer to a function in C/C++. Except that the C# compiler checks and ensures that the variable passed to the function is a reference whereas in C/C++, any value passed will be treated as pointer. This type of leniency in C/C++ is always a source of errors and bugs.

The copyright of the article Pointers in C# in C# Programming is owned by Jose Aniceto. Permission to republish Pointers in C# in print or online must be granted by the author in writing.

Go To Page: 1 2

Articles in this Topic    Discussions in this Topic