How can I implement implicit and explicit casting in ASP.NET Core

Dung Do Tien Dec 30 2020 285

I'm getting started with C#/.NET Core

I want to implement explicit and implicit casting between 2 classes

I have 2 classes 

 public class Student
 {
     public int Id { get; set; }
     public string Name { get; set; }
     public bool IsActivated { get; set; }
     public DateTime DateOfBirth { get; set; }

  }

  public class StudentDTO
  {
     public int Id { get; set; }
     public string Name { get; set; }
     public bool IsActivated { get; set; } 
  }

I want to convert Student to StudentDTO by using syntax StudentDTO studentDTO = (StudentDTO)student;

But I have compiled error 

Error when I convert Student to StudentDTO

How can I do it?

Have 1 answer(s) found.
  • H

    Huyền Trần thị Dec 30 2020

    You must implement implicit and explicit operator 

    Actually, we have some solutions to do that

    For example, I have 2 classes Student, StudentDTO

    I want to implicit and explicit casting Student to StudentDTO

    public class Student
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public bool IsActivated { get; set; }
        public DateTime DateOfBirth { get; set; }
    
    }
    
    public class StudentDTO
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public bool IsActivated { get; set; }
    
        public static explicit operator StudentDTO(Student student)
        {
            return new StudentDTO()
            {
                Id = student.Id,
                Name = student.Name,
                IsActivated = student.IsActivated
            };
         }
    }

    After that you can use this syntax anywhere : 

     StudentDTO dto = (StudentDTO) student;

    If you change explicit to implicit

     You can use this syntax :

     StudentDTO dto = student;

    I hope my solution will help you.

Leave An Answer
* NOTE: You need Login before leave an answer

* Type maximum 2000 characters.

* All comments have to wait approved before display.

* Please polite comment and respect questions and answers of others.

Popular Tips

X Close