C# Coding

These are questions related to the general C# coding.

[Main index]

Where are the header files?

There aren't any. C# does not use header files like C or C++ do. Instead, code is compiled into assemblies which may be referenced in a C# application.

(Contributed by Paul Parks)

[Section index] [Main index]

Does C# have a pre-processor?

Yes, though it does not provide macros via #define like C or C++. The #define directive may only be used to enable or disable a flag (such as #define DEBUG).

(More information coming.)

(Contributed by Paul Parks)

[Section index] [Main index]

How do I do conditional compilation?

Approximately the same way as in C or C++.

#if DEBUG
public void DebugMethod()
{
	// This is only compiled for debug builds
}
#endif

(More information coming.)

(Contributed by Paul Parks)

[Section index] [Main index]

How does foreach work?

Foreach works though the power of the IEnumerator/IEnumerable interfaces. A collection is required to implement IEnumerable to support the foreach operation. Once IEnumerable is implemented, calling foreach is as simple as this:

foreach(Object obj in someCollection)
{
   DoStuff(obj);
} 

This works because an IEnumerator object is created, and iterates through the collection for you. Using the ildasm tool, we can find that these two functions are roughly equivalent (minus some finally/IDisposable code in the foreach version that never gets called anyway). The order of iteration is always "logical" - single-dimensional arrays increment from 0 to Length-1. Multi-Dimensional arrays are iterated from "right to left" - foo[0][0] then foo[0][1] and so on.

If you're into that whole disassembly thing, here's an example of how it "really" works. The methods Main and OtherMain are roughly equivalent - compile and use ILDASM on the assembly if you don't believe me :)

static void Main(string[] args)
{
   foreach(object obj in al)
   {
      Console.Write(obj.ToString());
   }
}

static void OtherMain(string[] args)
{
   IEnumerator foo = al.GetEnumerator();
   while(foo.MoveNext())
   {
      Console.Write(foo.Current.ToString());
   }
} 
(Contributed by Nathan Acuff)

[Section index] [Main index]

Why didn't my string change?

In C#, string is considered a value type like basic types such as int or char. When passing a string object to a method, the string's value is copied to the parameter, not referenced. If you want to modify a string via a method, you have to pass it by reference like this:

private void MyMethod(ref string MyString)
{
    MyString = "Hello, world!";
}

The method call goes as follows:

private string s;
// ...
MyMethod(ref s);

All other non-basic types are always passed by reference.

(Contributed by Eric Bernard)

[Section index] [Main index]

What does a real C# developer snack on while coding?

Froot Loops, of course. That is, when the kids haven't finished off the box already.

(Contributed by Paul Parks)

[Section index] [Main index]