Creating instance of object dynamically

Yesterday while refactoring some code written by another developer I came across one thing at a lot of places one method was being used again and again

   1:  Public ClassName GetObject()
   2:  {
   3:  if object == null
   4:  create object
   5:  return object
   6:  }

That was essential logic but why rewrite…. there should be a generic way to accomplish this …

I came up with the idea of using Activator class in dot net…. which provides ability to create instances of objects dynamically.

here was my initial code

   1:   public static object CreateObject(Object obj)
   2:   {
   3:     if (obj == null)
   4:     {
   5:     return
Activator.CreateInstance(obj.GetType(),obj);
   6:     }
   7:    return obj;
   8:  }

but during execution I got following error “can’t get type of null object”, The problem was dot net does not allows to get type of null objects..

what now…. well! no worries at this stage generics comes handy by using generics it was just a piece of cake

Final Code:

   1:  public static T CreateObject<T>(T obj)
   2:  {
   3:  if (obj == null)
   4:  {
   5:  return Activator.CreateInstance<T>();
   6:  }
   7:  return obj; 
   8:  }
 
but what if the object passed, its instance creation 
requires parameterized constructor…
program will throw an exception at runtime in such 
cases… Why not prevent this during code writing

1:public static T CreateObject<T>(T obj)
where T : new()

2:  {
3:  if (obj == null)
4:  {
5:  return Activator.CreateInstance<T>();
6:  }
7:  return obj; 
8:  }
by adding new we have forced that the passed type 
should implement a parameter less constructor.

kick it on DotNetKicks.com Shout it

Advertisements
  1. Leave a comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: