Generic Method

Possibly save 2 hours of your time: There are times when you want to refactor your method. This happens when you have duplicate code that acts on two similar objects.

Scenario:

  • You have ObjectA
  • You have ObjectB
  • You have Method1(ObjectA)
  • You have Method2(ObjectB)
  • Both Method1 and Method2 has exact code that operates on the similar Object.

Solution:

  • First, make ObjectA and ObjectB inherit same interface IObject

                class ObjectA : IObject

                class ObjectB : IObject

  • Then, change your Method1 and Method2 to

                 Method<T>(T object) where T : IObject

  • Third, refactor your method 1 and 2 so that your caller will just call this method with ObjectA or ObjectB as parameter

                 Method(objectAorB);

 

 

 

Advertisements

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