Sachin Kumar
Sachin Kumar

Reputation: 9

how to pass generic list parameter into a method?

I am getting phone contacts into a list<> and saving it in a database. Below is my code.

This is my method to get the contacts-List

protected override void OnCreate(Bundle bundle) {
    base.OnCreate(bundle);
    try {
        SetContentView(Resource.Layout.Main);
        TextView txtcount = this.FindViewById<TextView>(Resource.Id.textView1);

        List<PersonContact> a1 = GetPhoneContacts();

        Phone gp = new Phone();

        gp.insertContact(a1);
    } catch (System.Exception ex) {
        alert(ex.Message);
    }
}

Via the following method I am trying to store contacts in database

[WebMethod]
public string insertContact<T>(List<PersonContact> a) {
    OpenConnection();
    if (a.Count > 0) {
        for (int i = 0; i < a.Count; i++) {
            string str = "insert into phone_contact (FirstName,LastName,PhoneNumber)values('" + a[i].FirstName + "','" + a[i].LastName + "','" + a[i].PhoneNumber + "')";
            SqlCommand cmd = new SqlCommand(str, con);
            cmd.ExecuteNonQuery();
        }
        return "1";
    } else {
        return "1";
    }
}

public class PersonContact {
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string PhoneNumber { get; set; }
}

I am getting an error while passing parameter

 gp.insertContact(a1);

Upvotes: 0

Views: 159

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1500535

Your method is generic, as it introduces a new type parameter T. That's what the <T> at the end of the method name means.

However, you don't use T anywhere - so just make it a non-generic method:

public string InsertContact(List<PersonContact> a)

At the same time, I would very strongly urge you to change the way you're doing database access: it's currently vulnerable to SQL injection attacks. Instead, you should use parameterized SQL: have one parameter for each of FirstName, LastName and PhoneNumber.

You're also returning "1" regardless of the input. Your method could be written more simply as:

// Consider renaming to InsertContacts, as it's not just dealing with a single
// contact
public string InsertContact(List<PersonContact> contacts)
{
    // You should almost certainly use a using statement here, to
    // dispose of the connection afterwards
    OpenConnection();
    foreach (var contact in contacts)
    {
        // Insert the contact. Use a using statement for the SqlCommand too.
    }
    return "1";
}

That's assuming you need the value returned at all - if you're always returning the same value, why not just make it a void method?

Upvotes: 7

Related Questions