MSDN's VS2010 Named and Optional Arguments (C# Programming Guide) tells us about optional parameters in C#, showing code like I'd expect:
public void ExampleMethod(int required,
string optionalstr = "default string",
int optionalint = 10)
Ok, but it also says:
You can also declare optional
parameters by using the .NET
OptionalAttribute class.
OptionalAttribute parameters do not
require a default value.
I read MSDN's OptionalAttribute page, and done searches online (which shows lots of people claiming OptionalAttribute parameters can't be consumed by C# -- I'm guessing these comments were made before C# 4?), but I can't find the answer to two questions:
If I use OptionalAttribute to define a C# parameter as optional:
what value will be used if I call that method and don't specify that parameter's value?
will that value be evaluated at compile time or runtime?
The rules are this:
For parameters of type object, Type.Missing is passed.
For other reference types, null is passed.
For value types, the default of the value type is passed.
For Nullable<T> this means that you will get a Nullable<T> instance which is equal to null (the HasValue property will return false)
Note that in the case of everything except parameters of type object, it's the equivalent of default(T).
I was a little surprised, as the C# 4.0 specification didn't indicate what the outcome would be, and I'd expect it to be there.
Also (as indicated by Scott Rippey in the comments), this is evaluated at compile-time, this is not a run-time operation, meaning that if you have calls to this method in other assemblies which are already deployed, and you change the optional value, the default passed to the method will not change unless you compile everything that makes the call against the method in the assembly.
Related
I'm a bit confused about the in parameter modifier:
I know if I write in before a parameter it a read only reference, which is faster then passing big stuff by value. According to the documentation https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/in-parameter-modifier it says that the in parameter modifier is optional on the callsite:
Specifying in for arguments at the call site is typically optional. There is no semantic difference between passing arguments by value and passing them by reference using the in modifier. The in modifier at the call site is optional because you don't need to indicate that the argument's value might be changed. You explicitly add the in modifier at the call site to ensure the argument is passed by reference, not by value. Explicitly using in has the following two effects:
First, specifying in at the call site forces the compiler to select a method defined with a matching in parameter. Otherwise, when two methods differ only in the presence of in, the by value overload is a better match.
Second, specifying in declares your intent to pass an argument by reference
When I use it in my code:
public static kAssetKind? DetermineAssetKind(in string extension)...
And I call it here:
...{FilePath = mainFile, Kind = DetermineAssetKind(Path.GetExtension(mainFile)) ?? kAssetKind.Other};
it's okay the string is passed by reference, but if I write specifically in before:
DetermineAssetKind(in Path.GetExtension(mainFile))
then I get an error that it could be passed by reference. So there is a difference between an in on callsite and it says "Second, specifying in declares your intent to pass an argument by reference" but I thought it will pass it by reference even if I don't use in at the callsite? And does it even make sense to pass a string as in reference because classes are reference?
I think you are misunderstanding the article.
The way I understand it is that considering the following method:
void Foo(in SomeBigValueType t)
{ ... }
The following two calls are the same:
SomeBigValueType v;
Foo(v);
Foo(in v);
Your issue seems to be unrelated to the article. in needs a storage location (aka variable). In your second example you aren’t passing one so you get an error; you’d get the same error with ref or out.
Can we use var keyword in methods optional parameter? Keyword var should be initialised while declared. Can't I use this as a default parameter, because default parameter is initialised while declared.
For example:
public void MyMethod(string param, var optionalParam = string.Empty)
When i try to do this then C# compiler is giving me an error, some one please explain.
Error:
The contextual keyword 'var' may only appear within a local variable declaration
Default parameter value for 'optionalParam' must be a compile-time constant
You can't use the var keyword for optional parameters, mostly because you can't use the var keyboard for any parameters, even non-optional parameters. var can only be used for local method variables, not for method parameters, fields or any other place. The compiler error here is clear and unambiguous.
That said, you have a second error there, also explained by the compiler, that you can't set an optional parameter's default value to a non-const value. string.Empty is non-const. You'll have to use null, or explicitly "" there.
First of all, String.Empty is not declared with const so it can't be used as the default value for optional parameters anyway. Use "" instead.
Though it seems perfectly okay to use var here, C# does not allow that.
According to the C# language specification section 10.6.1:
Method parameters The parameters of a method, if any, are declared by
the method’s formal-parameter-list.
formal-parameter-list:
fixed-parameters
fixed-parameters , parameter-array
parameter-array
fixed-parameters:
fixed-parameter
fixed-parameters , fixed-parameter
fixed-parameter:
attributes(opt) parameter-modifier(opt) type identifier default-argument(opt)
default-argument:
= expression
parameter-modifier:
ref
out
this
parameter-array:
attributes(opt) params array-type identifier
The formal parameter
list consists of one or more comma-separated parameters of which only
the last may be a parameter-array. A fixed-parameter consists of an
optional set of attributes (§17), an optional ref, out or this
modifier, a type, an identifier and an optional default-argument. Each
fixed-parameter declares a parameter of the given type with the given
name. The this modifier designates the method as an extension method
and is only allowed on the first parameter of a static method.
Extension methods are further described in §10.6.9.
Note how it says type under the fixed-parameter grammar? That means it needs a type there, not var.
On the other hand, here is what the specs say about local variable declarations where var can be used.
section 8.5.1 Local variable declarations
local-variable-declaration:
local-variable-type local-variable-declarators
local-variable-type:
type
var
local-variable-declarators:
local-variable-declarator
local-variable-declarators , local-variable-declarator
local-variable-declarator:
identifier
identifier = local-variable-initializer
local-variable-initializer:
expression
array-initializer
As you can see, for local-variable-type, it is either type or var. This shows that the specs treat type and var as different things. When it says type it must be a type, not var.
As the others have mentioned you cannot use var in the parameter list.
Now not having written the spec I can't tell you why you can't. However there is a very good reason why you shouldn't.
The parameter list is used to tell whoever calls the method what to put in. As a result it should clearly state that. If you use MyFunc(var param=Myconstant) I have no idea what type param should be.
I would guess that is why var is only allowed in local variables. Since local variables are not meant to be used by any other part of the program its fine if they don't spell out explicitly what they are.
MSDN's documentation on standard C# classes doesn't seem to contain what the default value for that type is. Am I not looking in the right place? Specifically, I am trying to figure out what the default value of XElement is.
I can always run my program and figure it out then, but I'd like a way to avoid that, if possible.
Edit: This page shows the default values for the native types, but I'm wondering about complex types.
The default value for all reference types is null.As stated in here:
The solution is to use the default keyword, which will return null for reference types and zero for numeric value types.
What is this code doing? Specifically the default(XX) part. I've never seen it before.
Entities.BizTalkRequestResult result = default(Entities.BizTalkRequestResult);
It's not a cast; it compiles to the default value of Entities.BizTalkRequestResult. For a reference type, e.g., that's probably null. See MSDN: http://msdn.microsoft.com/en-us/library/xwth0h0d(v=vs.80).aspx
There is a misconception; this is not casting at all. The default operator or function returns the default value. ex: 0 for int and null for reference types.
default is often used with generics (default(T)) because we don't know the actual type at compile time.
It gives you the default value for the particular type inside the parentheses. E.g. 0 for primitives numeric types like int or float, or null for reference types. It's useful particularly when the type could vary, and you want to write general code that is applicable for all possible types.
See below method definition.
What is it called in C# where the equals sign is in method parameter.
Does it default method parameter initialization??
public List<Iabc> MyMethod(out List<Ixyz> faces, Type typeXYZ = null, int flag = -1)
{
//...
//...
}
NOTE: Here Iabc and Ixyz are any Interfaces.
They're called optional (or named) arguments. MSDN usually has these things explained pretty well:
Named and Optional Arguments (C# Programming Guide)
When using named arguments, be aware that changing argument names will break code. (where named parameters are used)
Also, remember that the default value is actually stored in the call site meaning that if you at some later point change the default value, code that is calling the method and was compiled before the change, will still use the old value. it might not matter in all situations but its something to be aware of.
That's an optional argument in C# 4.0