0

I have a basic csharp objects question. I want to add my emails to a list and display their content.

I have created my object class:

 public class Email{
        public string EmailSubject {get; set;} 
        public string EmailContent {get; set;}
        public Email(String Subject, String Content)
        {
            EmailSubject = Subject;
            EmailContent = Content;
        }
    

Then I want to create a list and start making object to add to them and display.

    List<Email> Emails = new List<Email>();
    Emails.Add(new Email() {EmailSubject="MySubject", EmailContent="MyContent"} );

    Console.WriteLine();
    foreach (Email e in Emails)
    {
     Console.WriteLine(e);
    }

However, I am getting this error:

There is no argument given that corresponds to the required formal parameter 'Subject' of 'Email.Email(string, string)' 

I have also attempted to do this

Emails.Add(new Email(EmailSubject="MySubject", EmailContent="MyContent" ));

but my out is simply Email

What am i doing wrong?

1
  • 3
    This is basic constructor syntax. The first way fails because you do not have a constructor that takes no parameters and the second fails because you are not using the correct syntax (Emails.Add(new Email("MySubject", "MyContent" )) Commented Jan 7, 2021 at 12:55

3 Answers 3

3

you are trying to call parameterless constructor in new new Email() and its not specified

you can just add

public Email(){}

or use existing

new Email("Subject","Content")

For printing then you need to override and call method e.ToString()

add method to Email class

public override string ToString()
{
     return $"Subject-{EmailSubject} Content-{EmailContent};
}

then in foreach

Console.WriteLine(e.ToString());
Sign up to request clarification or add additional context in comments.

Comments

1

Your only constructor has 2 parameters hence the error referring to Email.Email(string, string) as you attempting to instantiate Email with zero parameters.

You should either remove the constructor from your code and use property intialisers as you already do. This works as the compiler will create a default constructor in the absence of any others.

new Email() {
    EmailSubject="MySubject",
    EmailContent="MyContent"
}

or leave the constructor and create an instance like this.

new Email("MySubject", "MyContent"}

Pick one, it makes little difference.

Comments

1

You can remove that constructor with two arguments and do this object initialization.

List<Email> Emails = new List<Email>();
Emails.Add(new Emails{ EmailSubject = "Something", EmailContent = "Also Something"});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.