C# Why would you use Call by Value? | Sololearn: Learn to code for FREE!
Новый курс! Каждый программист должен знать генеративный ИИ!
Попробуйте бесплатный урок
+ 1

C# Why would you use Call by Value?

*I am NOT asking the dif between value vs ref* I understand the difference. My question is why would you use call by value at all? It seems redundant. If you want the output to remain the same as the assigned value, why use (Example) ... static void Test(int x) { X=8; } static void Main() { Int a= 5; Test(a); Console.WriteLine(a) } ... When you could simply use: ... static void Main() { Int a=5; Console.WriteLine(a); } ... ??? Either way the output is 5. I hope this makes sense. Any input is appreciated.

12th Nov 2022, 8:02 PM
Sierra Mulligan
Sierra Mulligan - avatar
4 ответов
+ 5
It seems your question is about organizing (structuring) the code, why would we use functions at all. Functions (methods) are about code reusability. In larger programs, we may want to do certain things repeatedly but at different stages of the program. An important principle in programming is DRY = Don't Repeat Yourself. That's why we put those repeating blocks in separate methods. That way, if there is a bug or if you need to change the logic, you only have to change it in one place. Another point is separation of concerns. Every method should be responsible for only one thing, otherwise it can get very long and complex in a big program. When you read other people's code it should be easily understandable, even from the method names, what is the purpose of each block. This is also often referred to as SRP = Single Responsibility Principle.
13th Nov 2022, 5:31 AM
Tibor Santa
Tibor Santa - avatar
+ 4
In your example, it is probably a bit redundant. However, if you expand the concept to user input, then you can see how it starts to make sense. Next level after that, what if you want to do something to the user's input? And so on...
12th Nov 2022, 8:43 PM
Ausgrindtube
Ausgrindtube - avatar
+ 4
int marks [] = { 35, 25,45,78,90}; foreach( int m : marks) Console.WriteLine(m +" : "+ TestPassed(m) ; } static String TestPassed( int m) { if( m >= 35 ) return " Passed"; return "Fail"; } Check in this case, you just need to pass value to determine result. No need change value. If you need these check from other more courses having multiple subjects, checking in main rather than function use, will make code redundent.. Hope it helps..
12th Nov 2022, 9:06 PM
Jayakrishna 🇮🇳
+ 1
I'm very new to this, so I don't really see how user input affects it. If it's not too much trouble can you provide an example?
12th Nov 2022, 8:56 PM
Sierra Mulligan
Sierra Mulligan - avatar