views:

523

answers:

6

I am having trouble casting an object to a generic IList. I have a group of in statements to try to work around this, but there has to be a better way to do this.

This is my current method:

string values;

if (colFilter.Value is IList<int>)
{
    values = BuildClause((IList<int>)colFilter.Value, prefix);
}
else if (colFilter.Value is IList<string>)
{
    values = BuildClause((IList<string>)colFilter.Value, prefix);
}
else if (colFilter.Value is IList<DateTime>)
{
    values = BuildClause((IList<DateTime>)colFilter.Value, prefix);
}
else if (...) //etc.

What I want to do is this:

values = BuildClause((IList<colFilter.ColumnType>)colFilter.Value, prefix);

or

values = BuildClause((IList<typeof(colFilter.ColumnType)>)colFilter.Value, prefix);

or

values = BuildClause((IList<colFilter.ColumnType.GetType()>)colFilter.Value, prefix);

Each of these produces this compiler error: The type or namespace name 'colFilter' could not be found (are you missing a using directive or an assembly reference?)

In my example, colFilter.ColumnType is int, string, datetime, etc. I am not sure why this does not work.

Any ideas?

EDIT: This is C#2.0

EDIT #2

Here is the BuildClause method (I have overloads for each type):

private static string BuildClause(IList<int> inClause, string strPrefix)
{
    return BuildClause(inClause, strPrefix, false);
}

private static string BuildClause(IList<String> inClause, string strPrefix)
{
    return BuildClause(inClause, strPrefix, true);
}

private static string BuildClause(IList<DateTime> inClause, string strPrefix)
{
    return BuildClause(inClause, strPrefix, true);
}
//.. etc for all types

private static string BuildClause<T>(IList<T> inClause, string strPrefix, bool addSingleQuotes)
    {
        StringBuilder sb = new StringBuilder();

        //Check to make sure inclause has objects
        if (inClause.Count > 0)
        {
            sb.Append(strPrefix);
            sb.Append(" IN(");

            for (int i = 0; i < inClause.Count; i++)
            {
                if (addSingleQuotes)
                {
                    sb.AppendFormat("'{0}'", inClause[i].ToString().Replace("'", "''"));
                }
                else
                {
                    sb.Append(inClause[i].ToString());
                }

                if (i != inClause.Count - 1)
                {
                    sb.Append(",");
                }
            }

            sb.Append(") ");
        }
        else
        {
            throw new Exception("Item count for In() Clause must be greater than 0.");
        }

        return sb.ToString();
    }
+2  A: 

What does the function BuildClause() look like.

It seems to me that you can create BuildClause() as an extension method on IList, and you can append the values together. I assume that you just want to call .ToString() method on different types.

J.W.
This is C# 2.0, i dont think extension methods are available in 2.0. Are they? We are calling toString on the types, but for certain types we need to do some extra work.
Jon
Can you show us your BuildClause() method? It would help us to see what is wrong here. For generic type work on all cases, you need have the same method signature across all the types. If you call a method specific to DateTime,then it won't work for you.Thanks,
J.W.
Updated.. Thanks for the help.
Jon
I run your code.I did values = BuildClause(colFilter.Value, prefix); it seems OK. If you are sure colFilter.Value is a type IList<T>, it should be OK.
J.W.
that does not seem to work for me, I get a compiler error: What BuildClause overloads do you have?
Jon
A: 

The type for the IList must be known at compile time. Depending on what you want to do, you might be able to cast the list to an IList or IEnumerable (without generics) and then iterate over the objects

chris166
+2  A: 

If you use generics properly in C# 3.0, you can achieve what you need through implicit typing (int C# 2.0 you might need to specify the type). If your BuildClause method is made generic, it should automatically take on whatever type is passed in to its generic parameter(s):

public IList<T> BuildClause<T>(IList<T> value, object prefix)
{
    Type type = typeof(T);
    if (type == typeof(string))
    {
        // handle string
    }
    else if (type == typeof(int))
    {
        // handle int
    }
    // ...
}

public class ColumnFilter<T>:
    where T: struct
{
    public IList<T> Value { get; set; }
}

var colFilter = new ColumnFilter<string>
{
    Value = new { "string 1", "string 2", "string 3" }
}

IList<string> values = BuildClause(colFilter.Value, prefix);

With generics, you can drop the ColumnType property of your ColumnFilter. Since it is generic, along with your BuildClause method, you are easily able to determine the type by doing typeof(T).

jrista
+2  A: 

I am having trouble casting an object to a generic

Casting is a run-time operation.

Generic is compile-time information.

Don't cross the streams.

Also - if you used a decent sql parameterization generator - it will add the single quotes for you.

David B
+4  A: 

There's no way to relate method overloading and generics: although they look similar, they are very different. Specifically, overloading lets you do different things based on the type of arguments used; while generics allows you to do the exact same thing regardless of the type used.

If your BuildClause method is overloaded and every overload is doing something different (not just different by the type used, but really different logic, in this case - choosing whether or not to add quotes) then somewhere, ultimately, you're gonna have to say something like "if type is this do this, if type is that do that" (I call that "switch-on-type").

Another approach is to avoid that "switch-on-type" logic and replace it with polymorphism. Suppose you had a StringColFilter : ColFilter<string> and a IntColFilter : ColFilter<int>, then each of them could override a virtual method from ColFilter<T> and provide its own BuildClause implementation (or just some piece of data that would help BuildClause process it). But then you'd need to explicitly create the correct subtype of ColFilter, which just moves the "switch-on-type" logic to another place in your application. If you're lucky, it'll move that logic to a place in your application where you have the knowledge of which type you're dealing with, and then you could explicitly create different ColFilters at different places in your application and process them generically later on.

Consider something like this:

abstract class ColFilter<T> 
{
    abstract bool AddSingleQuotes { get; }
    List<T> Values { get; }
}

class IntColFilter<T>
{
    override bool AddSingleQuotes { get { return false; } }    
}

class StringColFilter<T>
{
    override bool AddSingleQuotes { get { return true; } }
}

class SomeOtherClass 
{
    public static string BuildClause<T>(string prefix, ColFilter<T> filter)
    {
        return BuildClause(prefix, filter.Values, filter.AddSingleQuotes);
    }

    public static string BuildClause<T>(string prefix, IList<T> values, bool addSingleQuotes) 
    {
        // use your existing implementation, since here we don't care about types anymore -- 
        // all we do is call ToString() on them.
        // in fact, we don't need this method to be generic at all!
    }
}

Of course this also gets you to the problem of whether ColFilter should know about quotes or not, but that's a design issue and deserves another question :)

I also stand by the other posters in saying that if you're trying to build something that creates SQL statements by joining strings together, you should probably stop doing it and move over to parameterized queries which are easier and, more importantly, safer.

Avish
+1  A: 

I don't understand the question. It works for me. It could be as simple as droping the cast? What am I missing?

using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApplication1 {

  class Foo<T> : List<T> {
  }

  class Program {
    static void Main(string[] args) {

    var a = new Foo<int>();
    a.Add(1);
    var b = new Foo<string>();
    b.Add("foo");
    Console.WriteLine(BuildClause(a, "foo", true));
    Console.WriteLine(BuildClause(b, "foo", true));

    }

    private static string BuildClause<T>(IList<T> inClause, string strPrefix, bool addSingleQuotes) {
      StringBuilder sb = new StringBuilder();

      //Check to make sure inclause has objects
      if (inClause.Count == 0) 
        throw new Exception("Item count for In() Clause must be greater than 0.");
      sb.Append(strPrefix).Append(" IN(");
      foreach (var Clause in inClause) {
        if (addSingleQuotes) 
          sb.AppendFormat("'{0}'", Clause.ToString().Replace("'", "''"));
        else
          sb.Append(Clause.ToString());
        sb.Append(',');
      }
      sb.Length--;
      sb.Append(") ");
      return sb.ToString();
    }

  }

}
johnnycrash