Why would you useFunc<string>
instead of just string
?
My question is specifically in regards to this repo.
The line in question is 22:
private static Func<string> getToken = () => Environment.GetEnvironmentVariable("GitHubToken", EnvironmentVariableTarget.Process);
getToken
encapsulates a method that has no parameters and returns a string
. What is the reason for not simply typing this variable to be a string?
Why would you useFunc<string>
instead of just string
?
The basic difference between Func and Action delegates is that while the former is used for delegates that return value, the latter can be used for those delegates in which you don't have any return value.
Func is generally used for those methods which are going to return a value, or in other words, Func delegate is used for value returning methods. It can also contain parameters of the same type or of different types.
Func is a generic delegate included in the System namespace. It has zero or more input parameters and one out parameter. The last parameter is considered as an out parameter. The Func delegate that takes one input parameter and one out parameter is defined in the System namespace, as shown below: Signature: Func.
I can see five reasons one might do this:
async
context, where you can await the results. You can await the function in a task directly, rather than having to also wrap the property as an awaitable method.By storing it as a Func<string>
, Environment.GetEnvironmentVariable
will be called each time the variable is accessed. Meaning if Environment.GetEnvironmentVariable
would return a different value on subsequent calls, you'll get the new value.
As far as I can tell, the only way Environment.GetEnvironmentVariable
will return a different value for the same input is if Environment.SetEnvironmentVariable is called.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With