Tuesday, August 14, 2012

Difference between "out" and "ref" parameter modifier?

What is the need of two similar type of parameter modifier? Was Microsoft a fool while engineering C# and how ECMA made the standard approved?


The questions are justified. See the difference below


Output parameters do not need initialization before you pass to methods; whereas Reference Parameters must be initialized before passing to method.

If you try to analyze why don't you need to initialize output parameters, then you can notice easily, methods are bound to assign values to parameters with "out" modifier before termination of the body.

Whereas, in case of parameters with "ref" modifier must be assigned before passing it to methods, otherwise compiler will understand that as an unassigned one. Here, we pass a reference to an existing variable.

Covered this aspect specifically for freshers and going to appear in interviews.

Trust, this becomes useful.



4 comments:

  1. Yes sir, as i understand I would like to add something Hope you ll like it.

    First thing : In any any method declaration, we have some parameter definition, in that we have some input parameters and some return value. But as we know that "return" return only one value at a time. If you want to get more than one value from the method then what to do? Yeah we have many ways of returning a value. But here microsoft has given output parameter with the use of "out" keyword. as many as u want to return a value it can be defined in method declaration. rest as u said already.

    Second thing: "ref", use of this keyword is depending on the concept of call by value and call by reference of method calling with parameter. whenever, you need to paas the reference of a variable in method as argument for that you need to define reference kind of parameter with the use ref keyword.

    Sir : If you give just a simple example explaining these, it would be better. after a long time i am writing to you.Rest I hope you are fine,doing well.

    Thanks

    ReplyDelete
    Replies
    1. See my previous post. That is here: http://souravmaitra.blogspot.in/2012/08/method-parameters-in-c.html. Hope that will fulfill your requirement

      Delete