ParamArrayAttribute Class (System)

Switch View :
ScriptFree
.NET Framework Class Library
ParamArrayAttribute Class

Indicates that a method will allow a variable number of arguments in its invocation. This class cannot be inherited.

Inheritance Hierarchy

System.Object
  System.Attribute
    System.ParamArrayAttribute

Namespace:  System
Assembly:  mscorlib (in mscorlib.dll)
Syntax

Visual Basic
<ComVisibleAttribute(True)> _
<AttributeUsageAttribute(AttributeTargets.Parameter, Inherited := True, AllowMultiple := False)> _
Public NotInheritable Class ParamArrayAttribute _
	Inherits Attribute
C#
[ComVisibleAttribute(true)]
[AttributeUsageAttribute(AttributeTargets.Parameter, Inherited = true, AllowMultiple = false)]
public sealed class ParamArrayAttribute : Attribute
Visual C++
[ComVisibleAttribute(true)]
[AttributeUsageAttribute(AttributeTargets::Parameter, Inherited = true, AllowMultiple = false)]
public ref class ParamArrayAttribute sealed : public Attribute
F#
[<Sealed>]
[<ComVisibleAttribute(true)>]
[<AttributeUsageAttribute(AttributeTargets.Parameter, Inherited = true, AllowMultiple = false)>]
type ParamArrayAttribute =  
    class
        inherit Attribute
    end

The ParamArrayAttribute type exposes the following members.

Constructors

  Name Description
Public method Supported by the XNA Framework Supported by Portable Class Library ParamArrayAttribute Initializes a new instance of the ParamArrayAttribute class with default properties.
Top
Properties

  Name Description
Public property TypeId When implemented in a derived class, gets a unique identifier for this Attribute. (Inherited from Attribute.)
Top
Methods

  Name Description
Public method Supported by the XNA Framework Supported by Portable Class Library Equals Infrastructure. Returns a value that indicates whether this instance is equal to a specified object. (Inherited from Attribute.)
Protected method Supported by the XNA Framework Supported by Portable Class Library Finalize Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method Supported by the XNA Framework Supported by Portable Class Library GetHashCode Returns the hash code for this instance. (Inherited from Attribute.)
Public method Supported by the XNA Framework Supported by Portable Class Library GetType Gets the Type of the current instance. (Inherited from Object.)
Public method IsDefaultAttribute When overridden in a derived class, indicates whether the value of this instance is the default value for the derived class. (Inherited from Attribute.)
Public method Supported by the XNA Framework Match When overridden in a derived class, returns a value that indicates whether this instance equals a specified object. (Inherited from Attribute.)
Protected method Supported by the XNA Framework Supported by Portable Class Library MemberwiseClone Creates a shallow copy of the current Object. (Inherited from Object.)
Public method Supported by the XNA Framework Supported by Portable Class Library ToString Returns a string that represents the current object. (Inherited from Object.)
Top
Explicit Interface Implementations

  Name Description
Explicit interface implemetation Private method _Attribute.GetIDsOfNames Maps a set of names to a corresponding set of dispatch identifiers. (Inherited from Attribute.)
Explicit interface implemetation Private method _Attribute.GetTypeInfo Retrieves the type information for an object, which can be used to get the type information for an interface. (Inherited from Attribute.)
Explicit interface implemetation Private method _Attribute.GetTypeInfoCount Retrieves the number of type information interfaces that an object provides (either 0 or 1). (Inherited from Attribute.)
Explicit interface implemetation Private method _Attribute.Invoke Provides access to properties and methods exposed by an object. (Inherited from Attribute.)
Top
Remarks

The ParamArrayAttribute indicates that a method parameter is a parameter array. A parameter array allows the specification of an unknown number of arguments. A parameter array must be the last parameter in a formal parameter list, and it must be a single-dimension array. When the method is called, a parameter array permits arguments to a method to be specified in either of two ways:

  • As a single expression of a type that is implicitly convertible to the parameter array type. The parameter array functions as a value parameter.

  • As zero or more arguments, where each argument is an expression of a type that is implictly convertible to the type of the parameter array element.

The example in the next section illustrates both calling conventions.

Note Note

Typically, the ParamArrayAttribute is not used directly in code. Instead, individual language keywords, such as ParamArray in Visual Basic and params in C#, are used as wrappers for the ParamArrayAttribute class. Some languages, such as C#, may even require the use of the language keyword and prohibit the use of ParamArrayAttribute.

During overload resolution, when compilers that support parameter arrays encounter a method overload that does not exist but has one fewer parameter than an overload that includes a parameter array, they will replace the method with the overload that includes the parameter array. For example, a call to the String.Split() instance method (which does not exist in the String class) is resolved as a call to the String.Split(Char[]) method. The compiler will also pass an empty array of the required type to the method. This means that the method must always be prepared to handle an array whose length is zero when it processes the elements in the parameter array. The example provides an illustration.

For more information about using attributes, see Extending Metadata Using Attributes.

Examples

The following example defines a Temperature class that includes a Display method, which is intended to display one or more formatted temperature values. The method has a single parameter, formats, which is defined as a parameter array.

Visual Basic

Public Class Temperature 
   Private temp As Decimal

   Public Sub New(temperature As Decimal)
      Me.temp = temperature
   End Sub

   Public Overrides Function ToString() As String
      Return ToString("C")
   End Function

   Public Overloads Function ToString(format As String) As String
      If String.IsNullOrEmpty(format) Then format = "G"

      Select Case format
         Case "G", "C"
            Return temp.ToString("N") + "  °C"
         Case "F"
            Return (9 * temp / 5 + 32).ToString("N") + "  °F"
         Case "K" 
            Return (temp + 273.15d).ToString("N") + "  °K" 
         Case Else
            Throw New FormatException(String.Format("The '{0}' format specifier is not supported", _
                                                    format))
      End Select                                                         
   End Function         

   Public Sub Display(<[ParamArray]()> formats() As String)
      If formats.Length = 0 Then
         Console.WriteLine(Me.ToString("G"))
      Else   
         For Each format As String In formats
            Try
               Console.WriteLine(Me.ToString(format))
            ' If there is an exception, do nothing.
            Catch
            End Try   
         Next
      End If
   End Sub
End Class


C#

using System;

public class Temperature
{ 
   private decimal temp;

   public Temperature(decimal temperature)
   {
      this.temp = temperature;
   }

   public override string ToString() 
   {
      return ToString("C");
   }

   public string ToString(string format)
   {
      if (String.IsNullOrEmpty(format))
         format = "G";

      switch (format.ToUpper())
      {
         case "G":
         case "C":
            return temp.ToString("N") + "  °C";
         case "F":
            return (9 * temp / 5 + 32).ToString("N") + "  °F";
         case "K": 
            return (temp + 273.15m).ToString("N") + "  °K";
         default:
            throw new FormatException(String.Format("The '{0}' format specifier is not supported", 
                                                    format));
      }                                                         
   }         

   public void Display(params string []formats)
   {
      if (formats.Length == 0)
      {
         Console.WriteLine(this.ToString("G"));
      }
      else  
      { 
         foreach (string format in formats)
         {
            try {
               Console.WriteLine(this.ToString(format));
            }
            // If there is an exception, do nothing.
            catch { }
         }
      }
   }
}


The following example illustrates three different calls to the Temperature.Display method. In the first, the method is passed an array of format strings. In the second, the method is passed four individual format strings as arguments. In the third, the method is called with no arguments. As the output from the example illustrates, the Visual Basic and C# compilers translate this into a call to the Display method with an empty string array.

Visual Basic

Public Module Example
   Public Sub Main()
      Dim temp1 As New Temperature(100)
      Dim formats() As String = { "C", "G", "F", "K" } 

      ' Call Display method with a string array.
      Console.WriteLine("Calling Display with a string array:")
      temp1.Display(formats)
      Console.WriteLine()

      ' Call Display method with individual string arguments.
      Console.WriteLine("Calling Display with individual arguments:")
      temp1.Display("C", "F", "K", "G")
      Console.WriteLine()

      ' Call parameterless Display method.
      Console.WriteLine("Calling Display with an implicit parameter array:")
      temp1.Display()
   End Sub
End Module
' The example displays the following output:
'       Calling Display with a string array:
'       100.00  °C
'       100.00  °C
'       212.00  °F
'       373.15  °K
'       
'       Calling Display with individual arguments:
'       100.00  °C
'       212.00  °F
'       373.15  °K
'       100.00  °C
'       
'       Calling Display with an implicit parameter array:
'       100.00  °C


C#

public class Class1
{
   public static void Main()
   {
      Temperature temp1 = new Temperature(100);
      string[] formats = { "C", "G", "F", "K" }; 

      // Call Display method with a string array.
      Console.WriteLine("Calling Display with a string array:");
      temp1.Display(formats);
      Console.WriteLine();

      // Call Display method with individual string arguments.
      Console.WriteLine("Calling Display with individual arguments:");
      temp1.Display("C", "F", "K", "G");
      Console.WriteLine();

      // Call parameterless Display method.
      Console.WriteLine("Calling Display with an implicit parameter array:");
      temp1.Display();
   }
}
// The example displays the following output:
//       Calling Display with a string array:
//       100.00  °C
//       100.00  °C
//       212.00  °F
//       373.15  °K
//       
//       Calling Display with individual arguments:
//       100.00  °C
//       212.00  °F
//       373.15  °K
//       100.00  °C
//       
//       Calling Display with an implicit parameter array:
//       100.00  °C


Version Information

.NET Framework

Supported in: 4, 3.5, 3.0, 2.0, 1.1, 1.0

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

Portable Class Library

Supported in: Portable Class Library
Platforms

Windows 7, Windows Vista SP1 or later, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008 (Server Core not supported), Windows Server 2008 R2 (Server Core supported with SP1 or later), Windows Server 2003 SP2

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.
Thread Safety

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.
See Also

Reference

Other Resources

Community Content

Koen Augustus
Klasse Database
Imports System.Data.Common, System.Configuration, System.Data.SqlClient

Public Class database

    Public Shared Function CreateParameter(ByVal name As String, ByVal value As Object) As DbParameter
        Dim par As New SqlParameter(String.Format("@{0}", name), value)
        Return par
    End Function

    Public Shared Function GetReader(ByVal name As String, ByVal sql As String, ByVal ParamArray param As DbParameter()) As DbDataReader
        Return GetCommand(name, sql, param).ExecuteReader
    End Function

    Public Shared Function GetReader(ByVal transaction As DbTransaction, ByVal sql As String, ByVal ParamArray param As DbParameter()) As DbDataReader
        Return GetCommand(transaction, sql, param).ExecuteReader
    End Function

    Public Shared Function GetCommand(ByVal name As String, ByVal sql As String, ByVal param As DbParameter()) As DbCommand
        Dim command As New SqlClient.SqlCommand(sql, GetConnection(name))
        If Not param Is Nothing Then
            command.Parameters.AddRange(param)
        End If
        Return command
    End Function

    Public Shared Function GetCommand(ByVal transaction As DbTransaction, ByVal sql As String, ByVal ParamArray param As DbParameter()) As DbCommand
        Dim command As New SqlCommand()
        command.CommandText = sql
        command.Connection = transaction.Connection
        command.Transaction = transaction
        If command IsNot Nothing Then
            command.Parameters.AddRange(param)
        End If
        Return command
    End Function

    Public Shared Sub ExecuteSQL(ByVal connection As DbConnection, ByVal transaction As DbTransaction, ByVal sql As String, ByVal ParamArray param As DbParameter())
    End Sub

    Public Shared Sub ExecuteSQL(ByVal name As String, ByVal sql As String, ByVal ParamArray param As DbParameter())
        Dim conn As SqlClient.SqlConnection = GetConnection(name)
        Dim command As New SqlClient.SqlCommand(sql, conn)
        command.Parameters.AddRange(param)
        conn.Close()
        conn.Open()
        command.ExecuteNonQuery()
        conn.Close()
    End Sub

    Public Shared Function GetDataTable(ByVal name As String, ByVal sql As String, ByVal ParamArray param As DbParameter()) As DataTable
        Dim d As New DataTable
        Dim dAdapter As New SqlDataAdapter(GetCommand(name, sql, param))
        dAdapter.Fill(d)
        Return d
    End Function

    Public Shared Function GetConnection(ByVal name As String) As DbConnection
        Dim conn As New SqlClient.SqlConnection(GetConnectionString(name))
        If conn.State = ConnectionState.Closed Then
            conn.Open()
        End If
        Return conn
    End Function

    Public Shared Function GetConnectionString(ByVal name As String) As String
        Return ConSetting(name).ConnectionString
    End Function

    Private Shared ReadOnly Property ConSetting(ByVal name As String) As ConnectionStringSettings
        Get
            Return ConfigurationManager.ConnectionStrings.Item(name)
        End Get
    End Property

    Public Shared Function ExecuteScalar(ByVal name As String, ByVal sql As String, ByVal ParamArray param As DbParameter()) As Object
        Dim obj As Object
        Dim command As DbCommand = GetCommand(name, sql, param)
        obj = command.ExecuteScalar

        Return obj
    End Function

End Class