briba
briba

Reputation: 2987

Generic object inside method

I have some doubts about generic object and I don't know if my idea can be implemented easily...

I have objects that implement the same interface, so the methods are almost equals besides the main object like the code below:

public bool Func1 (Bitmap img)
{
   Obj1                 treatments    = new Obj1 ();
   List<UnmanagedImage> unmanagedList = treatments.ExtractLetters(img);

   // Check image treatments
   if (!treatments.WasSuccessful)
      return false

   return true
}

public bool Func2 (Bitmap img)
{
   Obj2                 treatments    = new Obj2 ();
   List<UnmanagedImage> unmanagedList = treatments.ExtractLetters(img);

   // Check image treatments
   if (!treatments.WasSuccessful)
      return false

   return true
}

In this case, I don't want to duplicate the code. Is there any easy way to make this Obj1 and Obj2 generic? Because I could write only one function, and then the function could do a cast in the object, because the rest is the same.

Thank you!

Upvotes: 1

Views: 114

Answers (2)

D Stanley
D Stanley

Reputation: 152556

Only if Obj1 and Obj2 either implement an interface or inherit a base class that defines ExtractLetters and WasSuccessful. Otherwise they are unrelated methods that happen to have the same name.

If there is an interface or base class you could do:

public bool Func1<T>(Bitmap img) where T: ITreatments, new()
{
   T treatments = new T();
   List<UnmanagedImage> unmanagedList = treatments.ExtractLetters(img);

   // Check image treatments
   if (!treatments.WasSuccessful)
      return false

   return true
}

Upvotes: 2

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726569

Yes, there is - assuming that all Treatments implement a common interface ITreatments that provides ExtractLetters and WasSuccessful, you can do this:

interface ITreatments {
    List<UnmanagedImage> ExtractLetters(Bitmap img);
    bool WasSuccessful {get;}
}

public bool Func<T>(Bitmap img) where T : new, ITreatments
{
    T treatments    = new T();
    List<UnmanagedImage> unmanagedList = treatments.ExtractLetters(img);
    return treatments.WasSuccessful;
}

Now you can call this function as follows:

if (Func<Obj1>(img)) {
    ...
}
if (Func<Obj2>(img)) {
    ...
}

Upvotes: 8

Related Questions