Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Storing data into list with class

Tags:

c#

.net

list

I have the following class:

public class EmailData {     public string FirstName{ set; get; }     public string LastName { set; get; }     public string Location{ set; get; } } 

I then did the following but was not working properly:

List<EmailData> lstemail = new List<EmailData>();  lstemail.Add("JOhn","Smith","Los Angeles"); 

I get a message that says no overload for method takes 3 arguments.

like image 724
Nate Pet Avatar asked Dec 05 '11 21:12

Nate Pet


2 Answers

You need to add an instance of the class:

lstemail.Add(new EmailData { FirstName = "John", LastName = "Smith", Location = "Los Angeles"}); 

I would recommend adding a constructor to your class, however:

public class EmailData {     public EmailData(string firstName, string lastName, string location)     {         this.FirstName = firstName;         this.LastName = lastName;         this.Location = location;     }     public string FirstName{ set; get; }     public string LastName { set; get; }     public string Location{ set; get; } } 

This would allow you to write the addition to your list using the constructor:

lstemail.Add(new EmailData("John", "Smith", "Los Angeles")); 
like image 192
Reed Copsey Avatar answered Sep 21 '22 11:09

Reed Copsey


If you want to instantiate and add in the same line, you'd have to do something like this:

lstemail.Add(new EmailData { FirstName = "JOhn", LastName = "Smith", Location = "Los Angeles" }); 

or just instantiate the object prior, and add it directly in:

EmailData data = new EmailData(); data.FirstName = "JOhn"; data.LastName = "Smith"; data.Location = "Los Angeles"  lstemail.Add(data); 
like image 20
slandau Avatar answered Sep 22 '22 11:09

slandau