Hergine Richemont

Learning just for the fun of it

C# Track, Exercism #48 Two fer

Relevant link


Github solution: exercism-solutions

Exercism #48: Two fer

Learning Goal

Method overloading vs Optional argument

Notes

If you’ve read my recent posts, you should have noticed that I try to document task by task what I do for each exercise. I’ve decided to change that. To see my solution click on the link above to ge directly to the exercise solution on github.

I will use the posts now to gather information about the knowledge required to solve the problem but without reference to it. I hope yo like the new format, let’s get going


In C#, method oveloading and optional parameters can both let you call a method with fewer arguments, but they solve the problem differently.

1. Method overloading

You create multiple methods with the same name but different parameter lists:

You can then do:

The compiler chooses the appropriate method based on the arguments.

2. Optional parameter

You have one method, and give a parameter a default value:

is effectively treated as:

And you can still do:

The main difference

OverloadingOptional parameter
Number of methodsMultipleOne
Different behaviorEasy⚠️Can become conditional
Different parameter typesYes❌Not the purpose
Default valueNot required Yes
Simple APISometimesUsually
Useful when logis is genuinely different

When to use each?

Use optional parameter when:

The method does essentially the same thing, and one value is simply the normal/default choice.

Use overloading when:

Different ways of calling the method represent meaningfully different operations or require different logic.

In fact, you can combine them. A common pattern is to use overloading to provide a clean public API and have one implementation handle the actual work:

One important consideration

Optional parameters are compile-time defaults:

If another project compiles against your library and you later change “INFO” to “DEBUG”, aalready-compiled callers may still use “INFO” until they are recompiled.

So, for library/API design, overloads can sometimes be safer when the default behavior is important or likely to change.

Rule of thumb:

Same operation + sensible default → optional parameter.

Different ways of performing/expressing the operation → overload.


What would you add on the topic?

Subscribe
Notify of
guest
0 Comments
Oldest
Newest Most Voted