tags:

views:

142

answers:

3

I have a situation where i want to return List<> from this function

public DataTable GetSubCategoriesBySubCatID(Guid SubCategoryID)

So what i want is

public List<SubCategories> GetSubCategoriesBySubCatID(Guid SubCategoryID)

I know overloading is not supported on the basis of return type only,I just donot want to duplicate same code in both functions.

Whats the best way to achieve this without impacting the references which hold true for first function

+3  A: 

Use generics like below.

    public T GetSubCategoriesBySubCatID<T>(Guid SubCategoryID)
    {
        T value = ...;
        return value;
    }
Taylor Leese
And this is open to get categories in type of a "Car"?
yapiskan
@yapiskan - Not sure I understand? Are you referring to type constraints?
Taylor Leese
+5  A: 

Give them different names:

public DataTable GetSubCategoryTableBySubCatID(Guid subCatID)

public List<SubCategory> GetSubCategoryListBySubCatID(Guid subCatID)

Aside from anything else, that will make it clearer which method you're interested in when you're reading the calling code.

If those should be implemented in a common way, write a private method containing the common core, and call it from both of the public methods. For example, you might use a delegate to do the "I've found a result, add it to your collection" part, or use an iterator block:

// "action" will be called on each sub-category
private void FindSubCategoriesBySubCatID(Guid subCatID,
                                         Action<SubCategory> action)

private IEnumerable<SubCategory> FindSubCategoriesBySubCatID(Guid subCatID)
Jon Skeet
@jon- how would it fair if i convert this datatable to list<> by using reflection.Will it be a performance penalty.
Rohit
Reflection always involves a performance penalty. Quite how heavy that penalty will be will depend on exactly what you do.
Jon Skeet
A: 

I would define

public IEnumerable<SubCategories> GetSubCategoriesBySubCatID(Guid SubCategoryID);

The implementing class of this method is free to use any collection or container that implements IEnumerable{SubCategories}

Jehof