Rovdjuret
Rovdjuret

Reputation: 1528

I don't understand parameter declaration

I got this assignment which to declare a method like this...

public List<Contact> GetLastContacts([int count = 20])  
{  
    return this._entities.ContactsSet.ToList();  
}

What I don't understand and can't find info about is [int count = 20] as parameter...

Anyone got an explanation on what they mean?

/Best regards!

Upvotes: 0

Views: 151

Answers (3)

Honza Brestan
Honza Brestan

Reputation: 10947

I guess this might be a combination of two ways to write "optional parameter". In C#, you can define a method with optional arguments if you specify a default argument value with "assignment" like

public List<Contact> GetLastContacts(int count = 20)

You can then either call

GetLastContacts(count)

to specify the count, or

GetLastContacts()

which uses the default value of 20.

The usage of [ ] in your code might be POSIX standardized way to write optional parameters, which has no reason to be there at all as it's not supported by C# language nor its documentation standards.

Upvotes: 0

Rawling
Rawling

Reputation: 50114

public List<Contact> GetLastContacts(int count = 20) (no []) means the method has an int parameter called count, but that the parameter is optional, and if the caller leaves it out and just calls GetLastContacts() the default value for count is 20.

The square brackets are incorrect in C# code, but they can appear in documentation, tooltips etc. as an indication that the parameter is optional.

Upvotes: 3

Oded
Oded

Reputation: 499002

int count = 20 in a parameter declares it as a default value for the parameter. It makes the parameter optional for callers (or rather look optional for callers).

So, in a method calling it you can do:

var contacts = GetLastContacts(); // Will compile to GetLastContacts(20)

Or, to use a value to override the default:

var contacts = GetLastContacts(35); 

See Named and Optional arguments on MSDN.

Upvotes: 6

Related Questions