Raj Aththanayake's Blog Raj Aththanayake's Blog | C#

Keeping your C# code clean with Regionerate

17. October 2011

I came across with this really nice VS add-in called Regionerate, which allows you to group various member types into regions. I’m a fan of keeping code tidy and this add-in really helps me to organise the code.

It works on Visual Studio 2010 and only works with C#.

You can download the Add-In from here.

Once you install this tool, you are ready to use the Regionerate.

You can also change the settings of Regionerate, go to Tools and click Regionerate Settings.

To use the Regionerate, simply use the Ctrl +R. You should see a window with few options as below. Alternatively just right click on Text Editor and select ‘Regionerate this’ from the context menu.

image

 

As per the above options, you can create regions based on the member types (I.e public, private, and internal), regionalise by the member name, regionalise by the member type and the member name, order the members without and regions, and remove existing regions etc..

Below is a code sample on selecting the ‘Primary Code Layout’.

image

 

I strongly encourage you to have a look at this Add-In as it is very useful.

C#

Returning Null from a generic method

1. October 2011

 

A friend of mine asked me a question on this today. I hope you find this useful.

 

Consider this generic method….

   1: public T Get<T>() { 
   2: //return null
   3: }
   4:  

 

If you want to return null from a C# generic method, which contains the Type T parameter, there are 2 options.

a. Restrict the type parameter T, to be class constraint

 

   1: public T Get<T>() where T : class;
   2: {
   3:    //return null
   4: }
   5:  

Value types or Nullable Values types are not allowed. Reference types only.

 

b. Return default(T) which return null if T is a reference type or a Nullable value type

   1: public T Get<T>()
   2: {
   3:   return default(T);
   4: }
   5:  

 

Anything else will simply return their default values.  Here is a summary on both reference and value types….

 

//If T is a reference type

var retVal = f.Get<String>(); //return null

……….

//If T is a value type - int

var retValInt = f.Get<int>(); //return 0

……….

//If T is a value type - char

var retValChar = f.Get<char>(); //return '\0'

……….

//If T is a value type - bool

var retValBool = f.Get<Boolean>(); //return false

……….

//If T is a value type - enum

var retValEnum = f.Get<EnumType>(); // For enum types, if there are no enum values specified, then the return value is 0. If there are values, then the first enumeration returns as the default.

……….

//If T is a value type - struct

var retValStruct = f.Get<Bar>(); //Structs, returns the value of the struct

……….

//If T is a Nullable<Int32>

var retNullableInt = f.Get<Int32?>(); //return null

……….

C#