Hi @prajwal lama,
A constructor is a special method that is used to initialize objects. The advantage of a constructor, is that it is called when an object of a class is created. It can be used to set initial values for fields.
A parameterized constructor can take one or more parameters. Therefore, it can initialize different class objects to different values. This is an advantage over the default constructor.
Code you provided:
First, initialize the Message
class. It contains three public variables To
, Subject
and Content
. The parameterized constructorMessage()
initializes To
, Subject
, and Content
to the values given in to
, subject
, and content
respectively.
When we call the constructor, we pass the parameters to the constructor Message(IEnumerable<string> to, string subject, string content).
Below I've written a test that calls the constructor and added comments to the code to explain.
using MimeKit;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.ConstrainedExecution;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp1
{
internal class Program
{
static void Main(string[] args)
{
IEnumerable<string> TO = new[] { "test@123.com", "test@456.com" };
Message message = new Message(TO, "subject", "ABC");
Console.WriteLine(message.To + " " + message.Subject + " " + message.Content);
}
// Create a Message class
public class Message
{
public List<MailboxAddress> To { get; set; }
public string Subject { get; set; }
public string Content { get; set; } // Create multiple fields
public Message(IEnumerable<string> to, string subject, string content)
// Create a class constructor with multiple parameters
{
To = new List<MailboxAddress>();
To.AddRange(to.Select(x => new MailboxAddress("email",x)));
Subject = subject;
Content = content; // Set the value for To,Subject,Content
}
}
}
}
Best regards,
Lan Huang
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.