Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to assign out parameter in function? [closed]

Tags:

c#

.net

c#-4.0

I have a method that returns an object and also has an out parameter. The method calls another method that takes in the same out paramter as another out paramter. This gives a build error on the return statement:

The out parameter 'param1' must be assigned to before control leaves the current method

The code looks like:

public TypeA Method1(TypeA param1, out bool param2)
{
  /... some logic here .../
  SubMethod(out param2);
  /... some logic here .../
  return param1;
}

param2 is manipulated in SubMethod(), not in Method1(). Is there something else I need to do?

like image 379
4thSpace Avatar asked Oct 07 '22 15:10

4thSpace


1 Answers

In this case, I will assign a 'default' value. Regardless of bool, int, myFoo, etc. - set a default value.

public TypeA Method1(TypeB param1, out bool param2)
{
  param2 = false;   // default value;
  // or
  param2 = default(bool); // in cases where you are not sure what the default is

  /... some logic here .../
  SubMethod(out param2);
  /... some logic here .../
  return param1; // UPDATE: <- this is where you are receiving the exception
}

But you need to identify why the exception refers to 'param1' when param1 is clearly not at fault in this example ( for clarification : assuming TypeB : TypeA and is properly constrained).

I believe that passing param2 as an out parameter in SubMethod(...) removes the obligation to assign param2. However, you have not assigned anything to param1. Is there more going on here that has not been explained?

like image 120
IAbstract Avatar answered Oct 12 '22 10:10

IAbstract