C# Attributes, Using statement, and Properties

More adventures in C#!
There are a few new concepts I learned recently while working. As the title of this entry suggests, they are attributes, the using statement, and properties. While all three were new to me, they’re very logical (as one would expect with anything dealing with programming).
Attributes allow you to assign metadata to your code. An attribute goes directly before the data it describes. It’s encased in square brackets and is of the form Key(Value). For instance, if I want to describe who wrote a particular class and when, I could put // Peter Anargirou, 7/9/2008. However, that isn’t very structured. Instead I could put [Author(“Peter Anargirou”),Date(“7/9/2008”)] directly preceding the class declarations. Attributes can be programmatically referenced by the program in which they exist, making them very useful for code reflection.
The using statement is also very interesting. It’s of the format using ( object declarations here ) { …code…}. Anything declared in the using declaration is deallocated at the end of the using block. For example, you can open a file in the using declaration and not have to worry about closing it. When execution leaves the using block, the file is closed automatically. It’s similar to a try/catch/finally.
Lastly, properties are something new I recently discovered. They’re similar to accessor methods in other languages. Normally, if I have an int that I want to be able to access from outside the class it’s in, MyClass, I make it public. If I do that, then I might accidentally overwrite it when I that’s not what I intend to do. Also, there’s no way to check what I’m doing with it. For instance, I might not want it to store a value of 0, but with a public int, I have no way of enforcing that. Instead, I could make a private int and have accessor methods. I might have private int count, public int getCount(), and public void updateCount(int newCount). This is definitely the preferred way of doing things, but now when I want to retrieve the count from outside, I always have to say MyClass myClass = new MyClass(); int x = myClass.getCount();. To update the count, I have to use myClass.updateCount(42);. With properties, you can create accessor methods that invoke automatically while you treat the property like a public variable. For example, I now write

private int myCount;
public int count
get { return myCount; }
set { if ( value != 0) myCount = value; }

Now from outside I can simply write x = myClass.count to retrieve the value and myClass.count = 42 to update the value. Of course, it’s also checking that I’m not updating with 0. If I try to update with 0, it won’t actually update myCount. It’s clean and simple yet still provides the more complex checking that can be done with accessor methods. Very handy!