LogFAQs > #910003010

LurkerFAQs, Active DB, DB1, DB2, DB3, Database 4 ( 07.23.2018-12.31.2018 ), DB5, DB6, DB7, DB8, DB9, DB10, DB11, DB12, Clear
Topic List
Page List: 1
TopicCool function I wrote
Sahuagin
10/05/18 11:25:01 AM
#22:


checking some of my code, one place I use ref is on string validation

bool ValidateAndClean(ref string pString) {
...
}


the bool return value indicates whether the string changed, and the string changes to a different string if it was "messy" (whatever that means in the context of the method)

Magus 10 posted...
Yeah, multiple returns is the scenario I was thinking about with tuples being another option, although I suppose in the case where you're checking an error return value then out params are probably a little easier to use.

another scenario is method chaining. if you want to return values while method chaining you have to use out parameters. I have a tree control where I build the parts of the tree in a method chain:


treeControl
.BuildLayers()
.AddLayer<T1, T2>(t2 => t2.Parent, t1 => t1.Children, out var layer1)
.AddLeafLayer<T2>(out var layer2);

// do stuff with layer1 and layer2


It's maybe a bit overkill, but I just wrote a method that allows me specifically to assign in a method chain, which allows me to avoid a starting variable at the top.


// generic extension method on object
T AssignTo<T>(
...this T pValue,
...out T pTarget
) =>
...pTarget = pValue;


turns this:


var myValue =
___methodChainStart
___.DoOneThing()
___.DoSomething()
___.ThenDoSomethingElse()
___.Select(x => x.SomeProperty);

// do something else with myValue

to this:

methodChainStart
.DoOneThing()
.DoSomething()
.ThenDoSomethingElse()
.Select(x => x.SomeProperty)
.AssignTo(out var myValue);

// do something else with myValue


it's not a huge difference, but it reads a lot nicer since the assignment is now where the actual value is instead of at the opposite end

also with TryParse, I actually clean it up so that I can write this:

if (someText.IsNot<int>(out var intValue))
...return;

// make use of intValue

---
... Copied to Clipboard!
Topic List
Page List: 1