Pregunta

I know in C#, by default, referenced type variables are passed by reference to a method. I have a function which sometimes I just need its return value and sometimes both return value and the changes on the input object are needed outside of the function.

Then I wrote it as the following:

public static List<RuleSet> Load(XmlDocument dom= null)
{
   if (dom == null)
   {
       dom = new XmlDocument();
   }
   string path = ...
   dom.Load(path);
   List<RuleSet> ruleSets = new List<RuleSet>();
   // load the dom with file and read rules
   return ruleSets;
}

Sometimes I need the dom outside of the function and I call it Load(dom) and when I just need the return value I call it as Load().

However, I know if the parameter was declared with ref I couldn't set a default value for it and there must be a reason for if, but now I did it with no problem.

Then I suspect my approach to the problem (my function above) is correct or not, or could it be implemented in a better way?

¿Fue útil?

Solución

I know in C#, by default, objects are passed by reference

That's not correct. In C#, parameters are passed by value by default. But if that parameter is a reference type (like a class or interface), then it's the reference that's passed by value, not the object itself. If you actually want to pass by reference, you need to use ref, out or in.

However I know if the parameter was declared with ref I couldn't set a default value for it and there must be a reason for that

Yes, if a parameter is ref, then it basically means that it's an alias to a variable (local variable, field or array element). And a default value like null is not a variable.


What you're looking for could be solved by using two overloads instead of default value:

public static List<RuleSet> Load(out XmlDocument dom)
{
    dom = new XmlDocument();
    // rest of the method here
}

public static List<RuleSet> Load()
{
    XmlDocument ignored;
    return Load(out ignored);
}

Using ref XmlDocument dom and checking for null would also work, but I think it's less clear. The only advantage I can see with that is that it allows you to reuse the XmlDocument. But that's almost certainly a premature optimization.

Licenciado bajo: CC-BY-SA con atribución
scroll top