What is the difference between ref and out keyword in c




















Ref Keyword The ref keyword passes arguments by reference. This is very similar to the ref keyword. It is not compulsory to initialize a parameter or argument before it is passed to an out. It is not required to assign or initialize the value of a parameter which is passed by ref before returning to the calling method.

A called method is required to assign or initialize a value of a parameter which is passed to an out before returning to the calling method.

Passing a parameter value by Ref is useful when the called method is also needed to modify the pass parameter. Declaring a parameter to an out method is useful when multiple values need to be returned from a function or method. It is not compulsory to initialize a parameter value before using it in a calling method. In the case of pass by value, the value of the variable is passed whereas for the ref and out only the reference is passed.

Methods overloading is not possible in case one method takes a ref parameter and the other method out parameter. Method overloading is possible in case one method takes a ref argument and the other method takes a normal argument. The following example is perfectly valid for the method overloading. In C both ref and out keywords are used to pass arguments as a reference within a method. Any changes in the variable value inside the method will get reflected outside the calling method.

Sum out G ;. SetValue ref str ;. WriteLine str ;. WriteLine "Hello!! Geek" ;. Prev Next. When a variable passed to a method is preceded by out keyword the method returns it without using return keyword. The ref parameter should be initialized before it is passed to a method. On the other hand, the out parameter must be initialized inside the method it is passed to. While calling, declaring, or defining a method, ref parameter is explicitly declared as ref. On the other hand, while calling, declaring, or defining a method, out parameter is explicitly declared as out.

Leave a Reply Cancel reply Your email address will not be published.



0コメント

  • 1000 / 1000