Skip to content

Instantly share code, notes, and snippets.

@nadvolod
Last active October 8, 2023 21:01
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save nadvolod/a227f4a6d0c28b53749eef29d940da07 to your computer and use it in GitHub Desktop.
Save nadvolod/a227f4a6d0c28b53749eef29d940da07 to your computer and use it in GitHub Desktop.
How to call a default parameter in C#
//Clafication on default parameters
public static void Sum(int aNumber, double dNum = 5.5)
{
number += aNumber;
dNumber += dNum;
}
//CLARIFICATION
//To call this method without a parameter and get the default value, you can do
Sum(10);
//This will put 10 into int and 5.5 into the other parameter
//A MISTAKE
//The problem with this example is that when you call the method using Sum(10); above, it's an unclear reference to which method to call.
//Does the compiler call?
public static void Sum(int aNumber, double dNum = 5.5)
{
number += aNumber;
dNumber += dNum;
}
//OR will the compiler call this method?
public static void Sum(int aNumber)
{
number += aNumber;
}
//This is a mistake on Dr Tiffany's part. She should have renamed the method with a default parameter to something else.
//For example:
SumWithDefault(int aNumber, double dNum = 5.5)
{
number += aNumber;
dNumber += dNum;
}
//Then, we could call this method without ambiguity as such
SumWithDefault(10);
//This will place 10 into aNumber and 5.5 into dNum
@hanzalarohan123
Copy link

Thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment