An Array of a Generic Type

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • manishverma
    New Member
    • May 2007
    • 1

    An Array of a Generic Type

    Hi,
    I have been trying to declare an array of generic type, that I want pass as an argument of a function . I have a generic class with two properties;
    Code:
    public class ColumnValuePair<TKey>
    {
    	public string mstrColumn;
    	public TKey mValue;
    }
    I am trying to take an array of this class as an argument of a function, in some other class - something like this:
    Code:
    public Int32 GetIdentity(argTable, params ColumnValuePair<>[] argKey)
    {
    	StringBuilder sql = new StringBuilder();
    	sql.Append("SELECT " + this.Column + " FROM " + this.Table + " ");
    	sql.Append("WHERE ");
    	foreach (ColumnValuePair<int, int> key in argKey)
    	{
    		sql.Append(key.Column + " = ");
    		if (key.Value is string)
    		{
    			sql.Append("'" + key.Value + "'");
    		}
    		else
    		{
    			sql.Append(key.Value);
    		}
    		sql.Append(" AND ");
    	}
    	if (argKey.Length > 0)
    	{
    		sql.Remove(sql.Length - 5, 5);
    	}
    	Int32 id = (Int32)SqlHelper.ExecuteScalar(this.Connection, System.Data.CommandType.Text, sql.ToString());
    	return id;
    }
    Buth this throws error. Could any Guru help?!?
  • oohay251
    New Member
    • May 2007
    • 27

    #2
    The first problem is argTable is not assigned a type in your declaration.
    I'll assume string for demo purposes.

    If you know T at design-time, make the method generic

    public Int32 GetIdentity<T>( string argTable, params ColumnValuePair <T>[] argKey)

    so,

    ColumnValuePair <string> x,y,z;
    x = y = z = new ColumnValuePair <string>();
    GetIdentity<str ing>("blah",x,y ,x);

    If you know T only at run-time or T is going to vary with each method call, you can use the above with the complexities of Reflection, or perhaps just create a base class you can pass your types under:

    class CVPBase { }
    class ColumnValuePair <T> : CVPBase { }
    public Int32 GetIdentity(str ing argTable, params CVPBase[] argKey)
    ColumnValuePair <int> x;
    ColumnValuePair <string> y,z;
    x = new ColumnValuePair <int>();
    y = z = new ColumnValuePair <string>();
    GetIdentity("bl ah",x,y,x);

    Comment

    • SammyB
      Recognized Expert Contributor
      • Mar 2007
      • 807

      #3
      Well, I really cannot make any sense of your code. What are you trying to do? What error are you getting? What line? I'm especially having trouble with "argTable, params ColumnValuePair <>[] argKey" argTable is undeclared, parms is a reserved word, and ColumnValuePair does not have anything in the <>. Please give more details.

      Also, this information/book will help, http://www.wrox.com/WileyCDA/Section/id-291522.html

      Comment

      Working...