Currently when trying to do something in a method that takes an out parameter, I need to assign the value of the out parameter in the method body, e.g.
public static void TryDoSomething(int value, out bool itWorkerd)
{
itWorkerd = true;
if (someFavourableCondition)
{
// if I didn't assign itWorked variable before this point,
// I get an error: "Parameter itWorked must be assigned upon exit.
return;
}
// try to do thing
itWorkerd = // success of attempt to do thing
}
I'd like to be able to set a default value of the itWorked parameter so I don't have to arbitrarily set the value in the body of the method.
public static void TryDoSomething(int value, out bool itWorkerd = true)
{
if (someFavourableCondition)
{
// itWorked was already assigned with a default value
// so no compile errors.
return;
}
// try to do thing
itWorkerd = // success of attempt to do thing
}
Why is it not possible to assign a default value for an out parameter?
Default values are available for parameters passed by value. The parameter is still passed to the function but if the code omits the parameter, the compiler supplies the missing value.
Your proposed feature is quite different. Instead of the caller omitting to pass the value, you propose to allow the implementer of the function to omit setting the value. So, this is a quite different feature. Why was it not implemented? Here are some possible reasons:
Nobody thought to implement this feature.
The designers considered the feature and rejected it as not useful enough to be worth the cost of implementing.
The designers considered the feature and rejected it as being confusing because it uses similar syntax to default value parameters, but has a quite different meaning.
I appreciate this isn't exactly answering the original question, but I'm unable to contribute to the comments. I had the same question myself so found myself here.
Since C#7 now allows out parameters to effectively be variable declarations in the calling scope, assigning a default value would be useful.
Consider the following simple method:
private void ResolveStatusName(string statusName, out string statusCode)
{
statusCode = "";
if (statusName != "Any")
{
statusCode = statusName.Length > 1
? statusName.Substring(0, 1)
: statusName;
}
}
It felt intuitive to modify it like so:
private void ResolveStatusName(string statusName, out string statusCode = "")
{
if (statusName != "Any")
{
statusCode = statusName.Length > 1
? statusName.Substring(0, 1)
: statusName;
}
}
The intention was to not only declare the statusCode value, but also define it's default value, but the compiler does not allow it.
Even if it allowed you to give a default value like that, it would still require you to assign value for the parameter for all returns. So your default value will be overridden.
Default parameter values are the default value for parameters passed in to the method. You have to specify a variable to pass for an out parameter so that you can get the returned value.
Your first example, in a way, has a default, set at the beginning of the method.
The out method parameter keyword on a method parameter causes a method to refer to the same variable that was passed into the method. Any changes made to the parameter in the method will be reflected in that variable when control passes back to the calling method.
Declaring an out method is useful when you want a method to return multiple values. A method that uses an out parameter can still return a value. A method can have more than one out parameter.
To use an out parameter, the argument must explicitly be passed to the method as an out argument. The value of an out argument will not be passed to the out parameter.
A variable passed as an out argument need not be initialized. However, the out parameter must be assigned a value before the method returns.
Compiler will not allow you to use out parameter as default parameter because it is violating its use case. if you don't pass it to function you cannot use its value at calling function.
if you could call below function like TryDoSomething(123) then there is no use of out parameter because you will not be able to use value of itWorked
public static void TryDoSomething(int value, out bool itWorkerd = true)
{
if (someFavourableCondition)
{
// itWorked was already assigned with a default value
// so no compile errors.
return;
}
// try to do thing
itWorkerd = // success of attempt to do thing
}
If you have two calls to a method that uses 'out' or 'ref', and you want to avoid to split the method up in two, if one of the calls is not using these parameters, an elegant solution to avoid the warning from the compiler that "the value is not being used" (or something similar), is to use something like this:
method("hi", out _);
A method parameter declared with 'out' cannot have its value assigned by the caller. So a default value cannot be assigned during the call, either.
Also, you must always initialize an 'out' parameter in the method's body before using the parameter or returning from the method. This would overwrite any default value.
This is the whole point with the 'out' modifier. If you want a different behavior, check out the 'ref' and 'in' modifiers.
Related
Resharper gives a warning value assigned is not used in any execution path
private string FindMyId(string user, string defId) =>
defId = string.IsNullOrEmpty(defId) ? "defaultvalue" : defId;
I created above method to check if a value is empty and assign a default value to it anf return value in the same variable.It works functionaly. But it gives a message from resharper.
"value assigned is not used in any execution path"
Well, yeah. You reassign the parameter variable defId, but because there is only one statement in the method, there's no later method statement to read that saved value. In addition, because the defId parameter is not pass by ref, that change is only scoped to the method itself.
To get rid of the warning, just remove the variable assignment.
private string FindMyId(string defId) =>
string.IsNullOrEmpty(defId) ? "defaultvalue" : defId;
As posted, there's no use for the user parameter, and the method name FindMyId doesn't make logical sense for what the method is doing.
I'm in a situation where I am writing a method where the return value directly modifies a class which was used to supply paramaters to the method.
Computer.MatchingPassword = PasswordFinder.Find(Computer.Name, PasswordList)
Does assigning to a property of a passed parameter like this have any hazards?
Technically, your code sample doesn't assign to the parameter, since you passed a property of the Computer object.
In other words, you only gave the function "name", so assigning to a different property of the same object would have no effect.
Now, in the more general case, you are still safe. Even passing the whole object, by the time you assign the return value the method has already completed. Any changes you make won't do anything.
In other words, the following code is functionally equivalent:
string password = PasswordFinder.Find(Computer.Name, PasswordList);
Computer.MatchingPassword = password;
Clearly no problems there. This is true even if it was passed by ref, as again, the method is totally done with the object, so any changes to it won't matter.
Why it is necessary for the out parameter to be assigned to before it leaves the current method?
Can someone please elaborate me what is going inside the shell? Thanks in advance.
Why it is necessary for the out parameter to be assigned to before it leaves the current method?
Think of an out parameter as an extra return value. Just as you can't return from a non-void method without specifying the return value, you can't return from a method with an out parameter without setting a value for the parameter.
This in turn allows the argument for an out parameter to be definitely assigned after the method has completed, because it will definitely have been given a value by the method:
int value;
Foo(out value);
Console.WriteLine(value); // This is fine
Because it is designed in this way.That is the difference between out and ref parameters.By declaring an argument as out, the method guarantees that it will set the value of the argument.By ref, it doesn't have to.If you don't want an out use ref.
I am pretty new in C# (I came from Java) and I have the following doubt.
In a class I have the declarationf of this method:
public List<DataModel.MaliciousCode.MaliciousSmall> getList(DataModel.MaliciousCode.MaliciousSmall model, out int totalRecords)
{
.............................................
.............................................
.............................................
}
My doubt is related to the out keyword in the paramether list.
Reading the official documentation I have understand that this parameter is passed by reference (and that it could be not initialized).
So what exactly means? It means that in C# I have pointers?
out means that when this method will be called, the parameter totalRecords will be assigned some value from the method, and that value will be available to the caller.
out parameter modifier (C# Reference)
The out keyword causes arguments to be passed by reference. This is
like the ref keyword, except that ref requires that the variable be
initialized before it is passed. To use an out parameter, both the
method definition and the calling method must explicitly use the out
keyword.
For example, if you call your method like:
int totalRecords; //just declaration no initialization
var list = getList(new MaliciousSmall(), out totalRecords);
Console.WriteLine(totalRecords);// value from method.
at the end of method call, totalRecords will be assigned some value inside the method. It is mandatory for the method getList to assign/initialize some value to totalRecords. If it is not assigned any value in the method, a compile time error would occur. That is the reason why out parameters may or many not be initialized before using in method call.
inside your method, out int totalRecords must be assigned to any correct value depending on its type before the methods returned.
Even the totalRecords might be assigned to a value before calling this method (not encouraged), but the totalRecords still must be assigned to a value before it come out from method and other variable cannot do any value calculations or operations on it before it is assigned to any value, and this is different with other parameter modifiers such as ref.
For me, I might use the method return value as indication of method process, and out variable on other results that must come out from the method but the initialized value outside scope of the method can be ignored. safely handle multiple return values with out
Refer to accepted answer of this post, obvious difference is "You can say ++ on a pointer, but not on a ref or out." and ref is very closed to pointers but not out.
When we checked the Generated CIL Code difference between ref , out and pointers in C#, we can see this.
I'm implementing a TryParse(string s, Out object result) method.
If the parse fails, I would like not to touch the out parameter so any previous result will remain intact.
But VS2k8 won't let me. I have to set the value of the out object no matter what.
Should I just put result = result for the sake of pleasing the compiler? Am I missing something?
Assign null (or default(T) more generally). You must assign a value, that's what 'out' means.
Your suggestion of result = result won't work, because it's an out parameter - it's not definitely assigned to start with, so you can't read its value until you've assigned a value to it.
result = null;
is definitely the right way to go for an object out parameter. Basically use default(T) for whatever type T you've got. (The default operator is useful in generic methods - for non-generic code I'd normally just use null, 0, whatever.)
EDIT: Based on the comment from Boris, it may be worth elaborating on the difference between a ref parameter and an out parameter:
Out parameters
Don't have to be definitely assigned by the caller
Are treated as "not definitely assigned" at the start of the method (you can't read the value without assigning it first, just like a local variable)
Have to be definitely assigned (by the method) before the method terminates normally (i.e. before it returns; it can throw an exception without assigning a value to the parameter)
Ref parameters
Do have to be definitely assigned by the caller
Are treated as "definitely assigned" at the start of the method (so you can read the value without assigning it first)
Don't have to be assigned to within the method (i.e. you can leave the parameter with its original value)
result = null;
Just put some default value. For example the Int32.TryParse method puts zero.
You could use ref instead of out if you don't want to assign a value, although this must then be initialised by the caller.
You could throw an exception before the code that is supposed to set result.