Last active
October 8, 2023 21:01
-
-
Save nadvolod/a227f4a6d0c28b53749eef29d940da07 to your computer and use it in GitHub Desktop.
How to call a default parameter in C#
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks