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
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.
I'm going through an MVC tutorial and see this line of code at the beginning of a function:
private void PopulateDepartmentsDropDownList(object selectedDepartment = null)
After testing it out, I can see that the function works, but I do not understand how the function parameter works. What does object selectedDepartment = null do?
I have done a general internet search and have not yet been able to locate an answer.
I guess my question really has two facets:
What does the = null portion of the parameter do?
Is it something that can be done but not necessarily should be done?
It means that that parameter will be null, unless you decide to pass something. So in other words, its optional.
It can be done, and there is nothing wrong with it. Its pretty common practice.
It means that you can call
PopulateDepartmentsDropDownList()
or
PopulateDepartmentsDropDownList("something")
both because compiler will convert the first one to
PopulateDepartmentsDropDownList(null)
This feature is called Optional Arguments
I suggest you to read this blog post
the = null is the default value of the parameter, it is the functional equivalent as if you had
private void PopulateDepartmentsDropDownList()
{
PopulateDepartmentsDropDownList(null);
}
private void PopulateDepartmentsDropDownList(object selectedDepartment)
{
//Your code here.
}
So if you can call the function with no parameters PopulateDepartmentsDropDownList() it will call the 1 perameter version and pass in null.
This sets the argument to a default value (if not provided) and prevents a compile time error if the argument is not provided. See:
Setting the default value of a C# Optional Parameter
Basically this argument is now optional so you can call the function in either of these two ways:
PopulateDepartmentsDropDownList() //selectedDepartment will be set to null as it is not provided
OR
PopulateDepartmentsDropDownList(myObject) //selectedDepartment will become myObject
The optional parameters are nothing new in C# and I've known about that since the release of C# 5.0 but there is something I just came across. When I use Data Annotations for my MVC models such as the Required attribute I see this:
So I can do:
[Required(ErrorMessage="Something"]
However when I create my own methods with optional parameters like:
void Test(String x = null, String y = null) {}
I can pass arguments in both these ways:
Test(x = "Test") OR Test(x: "Test")
this while in the Required attribute I always have to use the = and if I use the : it will cause error.
for example:
Required(ErrorMessage:"Something") --> Compile time error
So what I see is that those Named Parameters are created differently than what I already knew about. And my question is How to make them for a method (How to create such Named Parameters like in the Required attribute).
An attribute has its own syntax. It uses the name=value form for named parameters.
For a normal method you can't use that form, you are stuck with the name:value form.
It would not be possible to use the name=value form for normal methods. The compiler would not be able to tell if you were trying to use a named parameter or if you were trying to assing a value to a variable and use the assignment as a parameter value.
Despite this syntax looking like a method call:
[Required(ErrorMessage="Something")]
An Attribute is a class, not a method. You aren't specifying an argument in the line above, you are initializing a property. See the example on the Attribute base class documentation to see what I mean.
The Attribute-specifying syntax is therefore similar to C#'s class initialization syntax:
new RequiredAttribute { ErrorMessage = "Something" };
There is currently no equivalent syntax in C# for specifying a named argument to a method.
If you do something like:
string y;
Test(y = "Test")
You can call a function with that syntax. But be careful... the y = "Test" is actually setting the variable y, and then passing that to the function! There is a side-effect there which is probably undesirable. Also "Test" is getting passed into parameter x of the Test function, not y because it's going in as the first parameter.
In short, you should always avoid using this syntax when calling a function, because it doesn't do what you're expecting.
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.