Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

overloading on basis of return type only

Tags:

c#

overloading

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

like image 805
Rohit Raghuvansi Avatar asked Mar 01 '23 08:03

Rohit Raghuvansi


1 Answers

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)
like image 133
Jon Skeet Avatar answered Mar 11 '23 15:03

Jon Skeet