C# Error Examples

C# developers face many of the same problems as users of other languages, plus many situations that are unique to the language and the underlying .Net framework. Klocwork detects a variety of situations in which code will cause failures, either immediately or over time, including:

NULL object references

For example, the following invalid use of a NULL object reference:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public class MyClass {
    public MyClass Create() {
        if (flag)
            return null;

        return new MyClass();
    }

    private int flag;
}

public class MyOtherClass {
    public void foo() {
        MyClass obj = Create();
        obj.foo();
    }
}

In this case, there are a set of conditions under which the unchecked usage of the returned object ‘obj’ will cause a runtime failure, and result in a Klocwork report of a possible defect.

Resource is not disposed

Likewise, considering contractual obligations, the IDispose interface requires referencing objects use the sole interface member Dispose) before allowing an implementing object to go out of scope.

For example, the following code will cause a defect to be reported:

Example: Resource is not disposed

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
using System;

namespace Leaky {
    class ResourceLeak {
        class MyDisposable : IDisposable {

            public void Dispose() {
                // Do something to remove associated resources
            }
        }

        static void foo() {
            IDisposable d = new MyDisposable();

            //Defect, function exits without closing the resource
        }
    }
}

Modifying this code to either explicitly invoke the Dispose method on the object d, or by using the “using” construct, will remove the defect:

1
2
3
static void foo() { using( IDisposable d = new MyDisposable() ) { }
    // No defect, Dispose is automatically invoked
}

Other languages

For examples of the types of defects Klocwork can detect in other languages please see the C/C++ error examples and Java error examples pages.