graycrow
graycrow

Reputation: 21

How to use generic for code reusability

I want to use Generic for reusability.

Code to be applied are listed below.

pubic Class Test < T >
{

    T item;

    ...

    public void set(T item)
    {
          this.item = item;

          // if (T type == int) {...}

          // if (T type == string) {...}

          abc();
    }

    private void abc()
    {
          ...
    }
}

Question1. I heard that using attribute is best solution in this situation. How do I implement this? Please, Tell me if you have any example. (Type will be added continually)

Question2. Is using Generic best solution about above example??

Thanks.

Upvotes: 0

Views: 381

Answers (2)

Lee
Lee

Reputation: 144206

You should avoid checking for particular types inside generic methods and classes. You could make set a template method and then override the type-specific behaviour inside subclasses which specify the type T e.g.

public class Test<T> {
    public void Set(T item) {
        this.item = item;
        this.OnSet(item);
        abc();
    }
    protected virtual void OnSet(T item) { }
}

public class IntTest : Test<int> {
    protected override void OnSet(int item) { ... }
}

public class StringTest : Test<string> { 
    protected override void OnSet(string item) { ... }
}

Upvotes: 4

Callum Bradbury
Callum Bradbury

Reputation: 956

I think you're looking for:

if (item is int) else if(item is string)...

Whether it's the best approach or not, I leave up to others.

Upvotes: 1

Related Questions