Home   Cover Cover Cover Cover


Question: Give reasons why C# is a safe language. Name the kinds of programming errors or hazardous situations that would be trapped by the C# compiler or the CLR?

Answer: C# and .NET promote code safety in several ways:

  • The compiler performs strict type checking in assignments, expressions, and method calls. It makes sure that variables always hold values of the correct types, that operands of expressions are type compatible with each other, and that methods are called with the correct number of parameters that have the correct types.

  • C# does not allow pointer arithmetic or type casts between pointers and other data types (except in code that is explicitly marked as unsafe). This makes sure that pointers always point to a legal object or have the value null.

  • The CLR throws exceptions if an array is accessed with an invalid index, if a null-valued variable is dereferenced, or if a type cast is applied to an object that does not have the expected target type.

  • The garbage collector automatically reclaims objects that are not referenced any more. This avoids stale pointers and memory leaks.

  • The versioning of .NET assemblies makes sure that the correct versions of DLLs are loaded, i.e. those versions that the compiler saw during type checking. This guarantees that the type checks of the compiler still hold at run time.