Is it possible to set the default C # parameter?

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

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

Another question: MyClass is a reference type, if there is no ref in front of it, it will pass a copy of MyClass to the method, but not the link?

thanks,

+4
source share
5 answers

Others correctly answered the optional part of the parameter: you can specify the default value for the parameter in C # 4. (There are various restrictions, for example, the required parameters must come before the optional ones, and the default value must be a time constant compilation.)

<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 default, but in the case of a reference type, the argument is a reference, not an object. Changes to the object will be visible to the caller, but if you change the parameter itself to refer to another object, this change will not be displayed to the caller. (This will not change the value of the calling variable.) For more information, see the article on parameter passing .

+5
source

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

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

John Skeet wrote a good article on this topic: " Passing Parameters to C # "

+10
source

The standard way to do this exact behavior in C # 3 and earlier is to overload the method in question:

 public void myMethod(int i, MyClass obj, int value=100){ // do whatever } public void myMethod(int i, MyClass obj) { myMethod(i, obj, 100); } 

And if MyClass is a reference type, then obj will be a reference to the MyClass object. adding the ref keyword will make obj link (as before) passed by reference . In other words, you could do:

 obj = new MyClass(); 

... and you must change the link that was passed to myMethod . Otherwise (without ref ) you will only change the local link; and the original link, no matter what was transferred to myMethod , will remain unchanged.

+3
source

You can do this in C # 4.0 for an optional parameter

+1
source

Source: https://habr.com/ru/post/1300881/


All Articles