Attention: We have retired the ASP.NET Community Blogs. Learn more >

Contents tagged with C# Tips and Tricks

  • C# - using keyword

    Most devs I work with are shocked to learn that the using keyword in the C# language is diatic. The obvious is for namespace inclusion but the less often seen use is for aliasing. For example, I hate having to reference the static members of ConfigurationSettings via the fully qualified name of System.Configuration.ConfigurationSettings. This is where aliasing can be cool; just give the class an alias with the using keyword like this:

      using cfg = System.Configuration.ConfigurationSettings;

  • Using inheritance to limit GetCustomAttributes array size

    OK, here is the deal – I want to get back an array of all the custom attributes assigned to my class. In my instance I have three custom attributes I have applied to the class. When I call GetCustomAttributes against the type I only want to see the custom attributes that I have added, not all the ones the ASP.NET runtime adds. When I ran my test I was getting an array of 13 attributes which included System.ComponentModel attributes that I don’t care about. How do you get rid of them? Create a BaseAttribute class derived from System.Attribute and then derive your attribute classes from this BaseAttribute class. Then use the GetCustomAttributes(System.Type, bool inherited) overload and pass in a reference to your BaseAttribute class as the type. This will cause your array to be limited to only attributes that derive from your base class; in my instance limiting to only the 3 custom attributes that I added!