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,
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#"
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With