Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.net reflection and the "params" keyword

In .net, is there a way using reflection to determine if a parameter on a method is marked with the "params" keyword?

like image 544
Lee Avatar asked Oct 15 '08 11:10

Lee


People also ask

What is the params keyword in C#?

params (C# Reference) By using the params keyword, you can specify a method parameter that takes a variable number of arguments. The parameter type must be a single-dimensional array.

Is it good to use reflection in C#?

Reflection in C# is used to retrieve metadata on types at runtime. In other words, you can use reflection to inspect metadata of the types in your program dynamically -- you can retrieve information on the loaded assemblies and the types defined in them.

Why is reflection expensive C#?

Because the common language runtime (CLR) stores information about the method's name in metadata, reflection must look inside metadata to learn which method on type "D" has the specified name. This logic alone is expensive.


2 Answers

Check to see if ParamArrayAttribute has been applied to the ParameterInfo object:

//use string.Format(str, args) as a test
var method = typeof(string).GetMethod("Format", new[] {typeof(string), typeof(object[])});
var param = method.GetParameters()[1];
Console.WriteLine(Attribute.IsDefined(param, typeof(ParamArrayAttribute)));
like image 69
Nathan Baulch Avatar answered Oct 19 '22 00:10

Nathan Baulch


Test to see whether the final ParameterInfo has ParamArrayAttribute applied to it.

like image 34
Jon Skeet Avatar answered Oct 19 '22 02:10

Jon Skeet