Tricky C# syntax for out function parameter
I'm fa开发者_高级运维miliar with using out to pass in a simple data type for manipulation, but I can't seem to figure out how to pass in this Queue<>
without causing a compile error. Any ideas?
Code:
Queue<SqlCommand> insertScriptQueue = new Queue<SqlCommand>();
private void UpdateDefaultIndicator(int newDefaultViewID,
out (Queue<SqlCommand>) insertScriptQueue)
UpdateDefaultIndicator(newViewID, out (Queue<SqlCommand>)insertScriptQueue);
You're passing in a reference type. No need to use out.
You shouldn't be initializing an out variable. If you need to modify an in-scope variable, use ref instead.
As Ed points out in his comment, "modify" may not give you the full idea of what's happening here - an out parameter of a reference type will by definition be an initialized object at the end of the function call. As most other answers have pointed out, if you want to pass in an initialized object, ref is the stronger choice.
Queue<SqlCommand> insertScriptQueue;
private void UpdateDefaultIndicator(int newDefaultViewID,
out Queue<SqlCommand> insertScriptQueue){/*body*/}
UpdateDefaultIndicator(newViewID,out insertScriptQueue);
That works fine for me... What error are you getting?
Why do you want a "out" ...here...why dont you return the type instead ? Let method return Queue<> insteasd of void..will that work for you?
The Queue is going to be passed by reference anyway, its not a value type. Just don't use 'out'. UPDATE: Pardon me, I was thinking of 'ref' - but the fact that you're passing a Queue data type in, and not just an unallocated reference, makes me think that you want to be using 'ref' anyway. Except of course that you don't need to use 'ref' because the Queue isn't a value type; its already going to be passed in 'by reference', by default.
make sure that you are assigning insertScriptQueue some kind of value inside of the UpdateDefaultIndicator method
The answer to the original question, by the way, is that you're casting to Queue, and the cast is returning an interim reference. That reference is not assignable, and so is not a legal out parameter. Erich's code implements the fix for this problem.
精彩评论