Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to control Type conversion in C#

Is there a way to control the type conversion in C#? So for example, if I have two types with essentially the same details, but one is used for the internal working of my application and the other is a DTO used for communicating with non-.Net applications:

public sealed class Player
{
  public Player(string name, long score)
  {
    Name = name;
    Score = score;
    ID = Guid.NewGuid();
  }

  public string Name { get; private set; }

  public Guid ID { get; private set; }

  public long Score { get; private set; }
}

public sealed class PlayerDTO
{
  public PlayerDTO(string name, long score, string id)
  {
    Name = name;
    Score = score;
    ID = id;
  }

  public string Name { get; private set; }

  // the client is not .Net and doesn't have Guid
  public string ID { get; private set; }  

  public long Score { get; private set; }
}

Right now, I need to create a new instance of PlayerDTO from my Player instance every time and I'm looking for a better, cleaner way of doing this. One idea I had was to add an AsPlayerDTO() method to the player class, but would be nice if I can control the type conversion process so I can do this instead:

var playerDto = player as PlayerDTO; 

Anyone know if this is possible and how I might be able to do it?

Thanks,

like image 859
theburningmonk Avatar asked Feb 05 '10 15:02

theburningmonk


2 Answers

You can implement an explicit convesion operator between the two types.

You could also consider using AutoMapper for the task.

like image 132
Mark Seemann Avatar answered Nov 07 '22 05:11

Mark Seemann


You can implement either implicit or explicit type conversion: http://msdn.microsoft.com/en-us/library/ms173105.aspx.

Alternately, if you want to avoid making each class having to know about the other, you can use either custom mapping or an existing mapping library like AutoMapper.

like image 22
Pete Avatar answered Nov 07 '22 06:11

Pete