[c#] Storing data into list with class

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.

This question is related to c# .net list

The answer is


You are attempting to call

List<EmailData>.Add(string,string,string)
. Try this:

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

Here's the extension method version:

public static class ListOfEmailDataExtension
{
    public static void Add(this List<EmailData> list, 
        string firstName, string lastName, string location)
    {
        if (null == list)
            throw new NullReferenceException();

        var emailData = new EmailData
                            {
                                FirstName = firstName, 
                                LastName = lastName, 
                                Location = location
                            };
        list.Add(emailData);
    }
}

Usage:

List<EmailData> myList = new List<EmailData>();
myList.Add("Ron", "Klein", "Israel");

You need to create an instance of the class to add:

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

See How to: Initialize Objects by Using an Object Initializer (C# Programming Guide)


Alternatively you could declare a constructor for you EmailData object and use that to create the instance.


This line is your problem:

lstemail.Add("JOhn","Smith","Los Angeles");

There is no direct cast from 3 strings to your custom class. The compiler has no way of figuring out what you're trying to do with this line. You need to Add() an instance of the class to lstemail:

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

And if you want to create the list with some elements to start with:

var emailList = new List<EmailData>
{
   new EmailData { FirstName = "John", LastName = "Doe", Location = "Moscow" },
   new EmailData {.......}
};

You're not adding a new instance of the class to the list. Try this:

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

List is a generic class. When you specify a List<EmailData>, the Add method is expecting an object that's of type EmailData. The example above, expressed in more verbose syntax, would be:

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

One way(in one line) to do it is like this:

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

How do you expect List<EmailData>.Add to know how to turn three strings into an instance of EmailData? You're expecting too much of the Framework. There is no overload of List<T>.Add that takes in three string parameters. In fact, the only overload of List<T>.Add takes in a T. Therefore, you have to create an instance of EmailData and pass that to List<T>.Add. That is what the above code does.

Try:

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

This uses the C# object initialization syntax. Alternatively, you can add a constructor to your class

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

Then:

lstemail.Add(new EmailData("JOhn", "Smith", "Los Angeles"));

  public IEnumerable<CustInfo> SaveCustdata(CustInfo cust)
        {
            try
            {
                var customerinfo = new CustInfo
                {
                    Name = cust.Name,
                    AccountNo = cust.AccountNo,
                    Address = cust.Address
                };
                List<CustInfo> custlist = new List<CustInfo>();
                custlist.Add(customerinfo);
                return custlist;
            }
            catch (Exception)
            {
                return null;
            }
        }

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"));

You need to new up an instance of EmailData and then add that:

var data = new EmailData { FirstName = "John", LastName = "Smith", Location = "LA" };

List<EmailData> listemail = new List<EmailData>();
listemail.Add(data);

If you want to able to do:

listemail.Add("JOhn","Smith","Los Angeles");

you can create your own custom list, by specializing System.Collections.Generic.List and implementing your own Add method, more or less like this:

public class EmailList : List<EmailData>
{
    public void Add(string firstName, string lastName, string location)
    {
        var data = new EmailData 
                   { 
                       FirstName = firstName, 
                       LastName = lastName,
                       Location = location
                   };
        this.Add(data);
    }
}

EmailData clsEmailData = new EmailData();
List<EmailData> lstemail = new List<EmailData>(); 

clsEmailData.FirstName="JOhn";
clsEmailData.LastName ="Smith";
clsEmailData.Location ="Los Angeles"

lstemail.add(clsEmailData);

Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to .net

You must add a reference to assembly 'netstandard, Version=2.0.0.0 How to use Bootstrap 4 in ASP.NET Core No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization .net Core 2.0 - Package was restored using .NetFramework 4.6.1 instead of target framework .netCore 2.0. The package may not be fully compatible Update .NET web service to use TLS 1.2 EF Core add-migration Build Failed What is the difference between .NET Core and .NET Standard Class Library project types? Visual Studio 2017 - Could not load file or assembly 'System.Runtime, Version=4.1.0.0' or one of its dependencies Nuget connection attempt failed "Unable to load the service index for source" Token based authentication in Web API without any user interface

Examples related to list

Convert List to Pandas Dataframe Column Python find elements in one list that are not in the other Sorting a list with stream.sorted() in Java Python Loop: List Index Out of Range How to combine two lists in R How do I multiply each element in a list by a number? Save a list to a .txt file The most efficient way to remove first N elements in a list? TypeError: list indices must be integers or slices, not str Parse JSON String into List<string>