No Free Time

July 11, 2008

How to create a default instance of a type T

Filed under: .net, c++ — Tags: , — andrewmyhre @ 4:41 am

A problem I’ve come across in the past when writing ORM solutions is when I need to create a new instance of generic type T but set to a NULL or 0 value. Value types I need to set to null but reference types I need to set to 0. How do I do the right thing? Here’s a bad way:

if (typeof(container) == typeof(int))
container = 0;
else if (typeof(container) == typeof(Customer))
container = null;

Using this method means lots of if … else if …else by checking type. How ugly! There has to be a better way, I thought. So I gave up and got on with something else.

Months later, it turns out there IS a better way: the default keyword:

t container = default(containerType);

This keyword gives you a NULL or 0 value based on the type you pass it. I don’t know whether it’s faster or more efficient, but hey, it’s a lot less code for you to write, and you can be pretty sure they’ve covered all the edge cases.

More information about the default keyword.

April 2, 2008

Constrain a generic Class/Method to a particular type

Filed under: .net, c++ — Tags: , — andrewmyhre @ 9:51 am

In C# you can constrain a generic type using the where T:Type syntax. For instance, my method to get a Url for a particular CMSObjectType (my base CMS domain object class) I declare the method like this:

public string GetUrl<T>() where T:CMSDataObject

This instructs the compiler that it will only accept types passed into the generic method which derive from CMSDataObject. The syntax is also valid for generic classes.

More information at MSDN: http://msdn2.microsoft.com/en-us/library/bb384067.aspx

January 20, 2008

Class Templates - Generic Classes in C++

Filed under: c++ — Tags: — andrewmyhre @ 12:05 pm

Since C# 2.0 we’ve been able to use the following syntax:

   82     public class MyClass<t>

   83     {

   84         private t obj;

   85         public MyClass(t theObject)

   86         {

   87             this.obj = theObject;

   88         }

   89

   90         public t doit()

   91         {

   92             return obj;

   93         }

   94     }

This can be accomplished in C++ in the following way:

    1 template <class T>

    2 class MyClass

    3 {

    4 public:

    5     MyClass(T* obj) ;

    6     ~MyClass();

    7     T* doit();

    8 private:

    9     T* theObject;

   10 } ;

   11

   12 MyClass::MyClass(T *obj)

   13 {

   14     theObject = obj;

   15 }

   16

   17 T* MyClass::doit()

   18 {

   19     return theObject;

   20 }

This is how we can implement strongly-typed object managers, as well as smart pointers.

Blog at WordPress.com.