Paul Stoner
Paul Stoner

Reputation: 1512

Get an Enumerator for Generic Object

I have made a thorough search for an answer and have not found one.

I want to write a method that translates an object into a dictionary object. When this method is called, the specific type of the input object will be provided.

Here is what I have thus far.

public static Dictionary<string, string> TranslateFormData<T>(Object form)
{
    T formData = (T)Convert.ChangeType(form, typeof(T));
    Dictionary<string, string> data = new Dictionary<string, string>();
    IEnumerator<KeyValuePair<string, string>> pairs = formData.GetEnumerator();

    while (pairs.MoveNext())
    {
        //Code left out for brevity
    }

    return data;
}

The usage would be something like this

Dictionary<string,string> data = FormData.TranslateFormData<FormCollection>(formData);

However, in the "TranslateFormData" method, the line

IEnumerator<KeyValuePair<string, string>> pairs = formData.GetEnumerator ( );

produces the following error:

'T' does not contain a definition for 'GetEnumerator' and no extension method 'GetEnumerator' accepting a first argument of type 'T' could be found (are you missing a using directive or an assembly reference?)

How can I specify the Type for object form in order to obtain an enumerator?

Upvotes: 1

Views: 412

Answers (2)

Noxymon
Noxymon

Reputation: 211

There is a problem with what you are asking, you are basically trying to force an object to implement the IEnumerable interface. The compiler does not know whether the object you are trying to convert will definetly be of type IEnumerable.

There for, you must declare the generic object as an object implementing the specified interface.

just add this line into your function declaration's end.

where T : IEnumerable

Upvotes: 0

clcto
clcto

Reputation: 9648

First off, just make the parameter of type T to avoid the cast:

public static Dictionary<string, string> TranslateFormData<T> ( T formData )

Then you can add a generic constraint so that T must implement IEnumerable< KeyValuePair< string, string > >:

public static Dictionary<string, string> TranslateFormData<T> ( T formData ) 
    where T : IEnumerable<KeyValuePair<string, string>>
{
    // don't need this line due to above
    //T formData = ( T )Convert.ChangeType ( form, typeof ( T ) );

    // rest the same.
}

Upvotes: 1

Related Questions