Variadic method parameters in C # params

1 minute read

background

I didn’t read the document properly even though I mainly do C # (I feel like I can read it seriously) C # related document and decided to remember it personally.
params was a document written as of July 20, 2015 … embarrassing (with self-discipline)

Notes on method parameter params

  • The type declared with params must be a ** one-dimensional array **
  • Only one params can be used **
  • ** When using multiple types declared other than params ** Declare params last
  • ** Can be called without passing parameters **, but the ** length of params is zero **

sample

public class VariableParameter
{
	public VariableParameter() { }

	public static string[] DeleteDuplicateFromArray(params string[] str)
	{
		return str.Distinct().ToArray();
	}

	//In this case, params is the last
	public static void ShowStringArray(params string[] strArr)
	{
		if (strArr.Length != 0)
		{
			foreach (var s in strArr)
			{
				Console.WriteLine(s);
			}
		}
		else
		{
			Console.WriteLine($"The length of the parameter{strArr.Length}is.");
		}
	}
}
class Program
{
	private static void Main(string[] args)
	{
		string[] strArr = { "test1", "test1", "test2", "test3", "test4" };

		var result1 = VariableParameter.DeleteDuplicateFromArray(strArr);
		VariableParameter.ShowStringArray(result1);

		//You can call it (the length of the list will be zero)
		var result2 = VariableParameter.DeleteDuplicateFromArray();
		VariableParameter.ShowStringArray(result2);
	}
}

Output result

test1
test2
test3
test4
The parameter length is 0.

Summary

When I read the docs, there are quite a few things I don’t know, just not catching up **.
It was interesting to see the new features, and the ** pattern matching extension ** and ʻusing declarations that can be used from C # 8.0` also made me feel like “I was able to do that …”.
It was good to change the focus on language learning. And you will love ** Microsoft ** more and more.

reference

Microsoft Docs

Tags:

Updated: