Home > Tags > NeXT
Page 1

Common C# Build-Time Errors: Part I

Here’s the situation:

You’ve written a program in C#. You’ve checked the flowcharts, examined your coding and developed your user interface.

You’re anticipating that everything will flow as smooth as silk. You’re ready to create a build of the program and, instead of seeing a beautiful, efficient result, you get several (often incomprehensible) error message. How did this happen?

Here are SOME ways that these errors occur:

#1 Undeclared Variables

C# throws an error message on undeclared variables. This most frequently happens in one of three ways:

1) The variable is not assigned a type. The code in a “for-next loop” that reads like this:

for (nextStep = 0; nextStep < 20; nextStep++) { // loop process }

should read like this:

for (int nextStep = 0; nextStep < 20; nextStep++) { // loop process }

2) The variable name is spelled differently. Variables are case sensitive in C#, which can lead to some careless errors:

for (int nextStep = 0; nextStep < 20; nextStep++) { int workerID = nextStep; Console.WriteLine("Worker ID #:" + WorkerId); }

The compiler will view “workerID” and “WorkerId” as two different variables and view “WorkerId” as undeclared.

3) The variable is declared in a different scope. In order to use variables both inside and outside a routine (such as a “for” loop or a “while “ loop), the variable must be declared outside the routine.

for (int nextStep = 0; nextStep < 20; nextStep++) { int workerID = nextStep; } Console.WriteLine("Worker ID #:" + workerID);

This code will not display the final number in the sequence, but will throw an error due to the workerID variable’s declaration sitting inside the for loop.

#2 Variable Conversion Errors

For developers new to C#, especially those coming from more intuitive platforms such as VB.Net or ASP.Net, the lack of flexibility with variable types can be a hurdle.

Here’s an example of a variable conversion that throws a build-time error:

class MyClass { static public float TripleFloat(float t) { float fResult = 3.0 * t; return fResult; } }

Since 3.0 is a “double”-type variable, the operation will return a “double”, not a “float”, and create a build-time error. The operation needs to recast the result as a “float” to avoid the conflict:

class MyClass { static public float TripleFloat(float t) { float fResult = (float)(3.0 * t); return fResult; } }

#3 Protection Level Conflicts

Some programmers may forget that the default protection level for a class is “internal” and the default level for any member in that class is “private”.

class MyFirstClass //default protection = internal { public void NameFunction(){ MySecondClass sc = new MySecondClass(); sc.strFirstName = "Harry"; sc.strLastName = "Potter"; Console.WriteLine("Name: " + sc.strFirstName...
more →
Benjamin Paul says: Surely the Visual Studio IDE should minimise the risk of most of these? These should be clearly obvious to the developer while...