Reputation: 504
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?
Upvotes: 0
Views: 195
Reputation: 802
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"});
Upvotes: 1
Reputation: 780
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());
Upvotes: 3
Reputation: 13059
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.
Upvotes: 1