Use of unassigned out parameter, c#

后端 未结 4 632
借酒劲吻你
借酒劲吻你 2020-12-29 01:06

I have very simple problem. I made a very simple function for you to demonstrate my problem.

static void Main(string[] args)       
{
    double[,] mydouble          


        
4条回答
  •  执念已碎
    2020-12-29 01:49

    In c# there are two very similar keywords, ref and out.

    Both of them pass values by reference, but the difference is:

    When you use ref the compiler will require you to assign your variable prior to calling the method.

    When using out it will not require this. This means that you will not be able to assume that the parameter has already been populated. You will not be able to read its value inside the method.

     

    To illustrate the problem, just imagine what would happen if someone else wrote this code to call your method:

    double[,] myUnassignedDouble;
    mynewMatrix(out myUnassignedDouble);
    

    Clearly the variable will never be assigned, which is bad.

     

    This leaves you with three options:

    1. Assign the variable each time you call the method and use void mynewMatrix(ref double[,] d)
    2. Assign the variable once, inside your method and use void mynewMatrix(out double[,] d)
    3. Assign the variable each time you call the method and use void mynewMatrix(double[,] d)

    The third option will work because so far you don't seam to need to reassign your variable. Obviously that might change as your code becomes more complicated. I assume you did have your reasons for using out in the first place?

提交回复
热议问题