Category Archives: C#

This is a category targeting C#.NET specific posts.

Useful Information on Data Contracts

I’m beginning to learn about the C# attributes [DataContract] and [DataMember]. Data Contracts in C# are a loose set of rules that are defined for a client and server to communicate through, C# has built in Data Contracts defined for default classes such as ints, strings, etc. Before .NET 3.5 SP1 any custom class, structure or enumerable object would require adding an attribute [DataContract] to the object definition; as well as adding [DataMember] to each property that would need to be serialized to XML.

I found a post on stack overflow which brings up a good question, and an even better reply. I feel the original author did a fine job of explaining it, so I felt linking to the post and grabbing a screen shot would do them more justice than paraphrasing.

The original link.


And the response


(Views: 303)

Statement Keywords Fixed, Checked and Unchecked

Fixed Block Type

C# uses a garbage collector to clean up memory leaks and take care of unused data storage variables. Fixed ensures that the variable declared inside it’s block will not be touched by the garbage collector. Because this presents a potential issue with memory leaks the fixed keyword block can only be used in methods declared with the “unsafe” keyword. This requires special permissions that some systems will block. The following is an example from MSDN.

unsafe static void TestMethod()

    // Assume that the following class exists. 
    //class Point  
    //    public int x; 
    //    public int y;  

    // Variable pt is a managed variable, subject to garbage collection.
    Point pt = new Point();

    // Using fixed allows the address of pt members to be taken, 
    // and "pins" pt so that it is not relocated.

    fixed (int* p = &pt.x)
        *p = 1;


Checked Block Type

The checked block type is used to make the compiler check for overflow values on any integer calculations. This is useful when performing an operation on a variable and assigning the result to an integer. The compiler does not detect overflow values on non-static variables, so the checked code block is required to enforce it. Here is a code sample from MSDN.

// If the previous sum is attempted in a checked environment, an  
// OverflowException error is raised. 

// Checked expression.
Console.WriteLine(checked(2147483647 + ten));

// Checked block. 
    int i3 = 2147483647 + ten;

Unchecked Block Type

The unchecked block type will allow an integer assignment to overflow instead of throw an error. An example of this from MSDN. The resulting int1 will be equal to “-2,147,483,639”

    int1 = 2147483647 + 10;
int1 = unchecked(ConstantMax + 10);

(Views: 278)