1

I recently discovered that you can define multiple methods with the same name as long as their arguments differ (I believe it's called method overloading). So for example, in a script I have a method called getDate(int date) and another called getDate(). The only differences between these methods is that the one that doesn't accept an argument uses a static integer defined in the class instead of the date argument.

I've used this logic for at least 5 different methods in the class, however it seems very messy to be duplicating code like this. Is there a more elegant solution?

3
  • Please show us the code you're asking about. Descriptions of code aren't that useful as they leave too much to the imagination and tend to be incomplete or inaccurate. Commented Apr 23, 2019 at 21:00
  • 5
    How about public DateTime getDate() { return getDate(staticInt); }? This would reuse the overload with the parameter by calling it, instead of copying the code. In any case, you should probably post your code so that we can see exactly what we're dealing with here, the devil is in the details and all that. Commented Apr 23, 2019 at 21:00
  • @LasseVågsætherKarlsen Man that's so simple and exactly what I need! Thanks very much. Commented Apr 23, 2019 at 21:07

2 Answers 2

3

Typically, its best to have one function that does the meat of what you're trying to achieve, while others invoke that function (or each other) to avoid duplicating actual logic.

I'll use your example:

Date GetDate(int date) {
    // -- do whatever you do here
    return DoAThing(date);
}

Date GetDate() {
    return GetDate(staticVar);
}

This way, if you want to change how you get a date, you won't have to change your code in multiple places, and when you modify GetDate(int date), your other functions that invoke it will simply follow suit.

Sign up to request clarification or add additional context in comments.

1 Comment

Oops. I didn't see that @Lasse Vågsæther Karlsen basically already answered this since it was in a comment. But we are basically saying the same thing :)
-1

Just call the methods as needed e.g.

//To Get the Date normally
DateTime date = getDate();
//Otherwise
date = getDate(1, DateTime.Today);

You should not have a problem calling them. They should be overloaded correctly by unity because I checked it with my editor.

1 Comment

This is not the asker's problem.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.