Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I give a C# parameter a default value?

Tags:

c#

In C# can we do the following like C++?

public void myMethod(int i, MyClass obj, int value=100){

}

Another question is MyClass is a reference type, if there is no ref before it, it will pass a copy of the MyClass into the method but not the reference?

thanks,

like image 980
5YrsLaterDBA Avatar asked Dec 01 '22 06:12

5YrsLaterDBA


2 Answers

Not in C# up to C# 3 (which is the current version). In C# 4 you can have optional parameters with default values.

Regarding the question about MyClass and ref, parameters are passed by value. For reference types, you could say that the "value" of a variable (or argument) is the reference to the instance, so if you modify properties on the MyClass instance, you modify the same instance as the caller has a reference to.

Jon Skeet has written a good article on the subject: "Parameter passing in C#"

like image 55
Fredrik Mörk Avatar answered Dec 04 '22 22:12

Fredrik Mörk


Others have correctly answered the optional parameter part: you can specify a default value for a parameter in C# 4. (There are various restrictions, e.g. mandatory parameters have to come before optional ones, and the default value has to be a compile-time constant.)

<gratuitous plug>See C# in Depth, 2nd edition, chapter 13 for more details</gratuitous plug>

For the "parameter passing" aspect - all arguments are passed by value by default, but in the case of reference type the argument is a reference, not the object. Changes to the object will be visible to the caller, but if you change the parameter itself to refer to a different object, that change won't be visible to the caller. (It won't change the value of the caller's variable.) See my article on parameter passing for details.

like image 22
Jon Skeet Avatar answered Dec 04 '22 21:12

Jon Skeet