'how can I create a new variable with the same data type of a specific variable in C#?

I want to create a new variable in the same data type of my variable Message. How can I do that?

I tried the following code. but I got an error.

MessageDTO Message;
var Message2 = new Message.GetType();

Error:

Message is a variable but is used like a type.

Here is my code:

public string Send(MessageDTO message)
{
     MessageDTO Message2 = new MessageDTO();
     if (message is Email)
     {
         Message2= new Email();
     }else if(message is SMS)
     {
         Message2= new SMS();
     }
    // rest of code ...
 }

Where

 public class MessageDTO
 {
        public int Id { get; set; }
        public MessageType Type { get; set; }
        public string? Subject { get; set; }
        public string? TextBody { get; set; }
        public string? HTMLBody { get; set; }
        public DateTimeOffset SendDate { get; set; }
        public DateTime SendTime { get; set; }
 }

public class Email : MessageDTO
{
   public string From{ get; set; }
   public string To{ get; set; }
}



 public class SMS : MessageDTO
 {
   public string SenderLine{ get; set; }
   public string[] To{ get; set; }
 }

I want to make my code open for extension, but closed for modification (i.e. If I add other types of messages, the Send method remains unchanged.). The Send method becomes shorter like this:

public string Send(MessageDTO message)
{
     MessageDTO Message2 = new Activator.CreateInstance(Message.GetType());
     // rest of code ...
 }


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source