C# Generics Question

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • pvenky
    New Member
    • Feb 2008
    • 1

    C# Generics Question

    If I call an overloaded method, say Convert.ToSingl e and the argument I pass is of generic parameter type T, which overloaded method will this call get bound to?

    Here is the code snippet:

    Code:
    internal void SomeMethod<T>(T arg1)
    {
       ...
       float fValue = Convert.ToSingle(arg1);
       ...
    }
    The compiler does not seem to care, may be because there exists an overload which takes an "object" type argument, but I am hoping this gets bound at run-time to the appropriate overload based on the actual type of arg1.

    Prasanna.
  • Chrace
    New Member
    • Feb 2008
    • 6

    #2
    Convert.ToSingl e( Object object ) does exist and might be why the compiler eats it. Doesn't mean it will work though.

    Without having tested it I would imagine calling Convert.ToSingl e with Object type parameter would try the possibilities, if failing it would look for an overloaded method on the object and if not found throw an exception.

    If you want to be 100% sure the code your own Switch with cases for TypeOf(object) for the parameters you would expect. If not in your list of types then throw an exception. At least you would know exactly what is going on.

    Or run a few hundred tests. :)

    -Chrace

    Comment

    Working...