What are params, in, out, and ref keywords in C# ?
What are params, in, out, and ref keywords in C#?
252
19-Jun-2025
Ponu Maurya
23-Jun-2025In C#, the keywords
params,in,out, andrefare used to control how arguments are passed to methods. They allow more flexible method signatures, especially when dealing with dynamic argument counts or modifying variables inside a method. Here's a breakdown of each:params– Variable Number of ArgumentsThe
paramskeyword allows you to pass a variable number of arguments of a specified type to a method. It must be the last parameter in the method signature, and only oneparamsparameter is allowed.Example:
You can call it like:
Use Case: Simplifies calling methods with a list of values without explicitly creating an array.
ref– Pass by Reference (Input/Output)The
refkeyword is used when a method needs to read and modify the caller's variable. The caller must initialize the variable before passing it.Example:
Use Case: When you want the method to change the original value passed from the caller.
out– Output Parameter (Only for Returning)The
outkeyword is used to return multiple values from a method. Unlikeref, the variable does not need to be initialized before being passed. However, the method must assign a value before returning.Example:
Use Case: Useful when you want to return more than one value from a method, especially before
TupleorValueTuplebecame popular.in– Pass by Reference (Read-Only)Introduced in C# 7.2, the
inkeyword passes arguments by reference, but they are read-only inside the method. It improves performance for large value types by avoiding copies, while still preventing modification.Example:
Use Case: Best used with large structs to avoid copying but ensure immutability.
Summary Table
paramsrefoutinWhen to Use What?
paramsfor flexible argument counts.refto read and modify a variable.outto return multiple results.infor performance on large structs with read-only intent.