简体   繁体   中英

Is there a proper work-around for overloading methods that need to take the same value types, or should it just be avoided?

I'm programming in c# and this is more of a best practices question.

I wanted to create an overloaded method and accidentally made two methods with the same value types as arguments. I wanted to use the same method name to keep things simple when writing code later so I added another int argument as a throw-away to the overload just to separate it from the first method. This doesn't seem like a good coding practice to me, but it did work.

Example here:

public static void SetBalance(Customer cust, int index)
{
    cust.Balance = balanceList[index];
}

public static void SetBalance(Customer cust, int value, int notUsed)
{
    cust.Balance += value;
}

My question: Is there a more clever or more appropriate way to work around having the same value types as method arguments in an overload, or is simply creating a new method with a different name the best solution?

Thank you for your help.

You would do better to name the first method something like RefreshBalance , since the resulting value of the customer's balance is not related to any arguments present in the method.

The second method would be better named something like AdjustBalance or IncrBalance for similar reasons. Two methods with plainly different behaviors should not have the same name.

The problem I see here is the naming convention. Both of these methods perform different operations so you should give them proper names SetBalance() and AddBalance() etc.

When you overload a constructor you shouldn't have two constructors with the same argument pattern as

public static string myConstruct(Customer cust, int index){}
public static string myContsruct(Customer cust, int age){}

As an example the two constructors have the same argument pattern so you'll end up with a error when compiling. To get around this just swap the arguments around on the second constructor as

public static string myContruct(Customer cust, int index){}
public static string myContruct(int age, Customer cust){}

This will avoid any conflicts.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM