Anonymous object as generic type

41 Views Asked by At

I have the following generic interface:

public interface IDatabaseEntity<out T>
{
    public T GetKey();
}

Now, I define several entities which all implement this interface. An example:

public class Player : IDatabaseEntity<Guid>
{
    public Guid Id { get; set; }
    // Other fields...

    public Guid GetKey() => Id; // Implement the interface
}

This all works fine, but now I have an entity which is uniquely defined by multiple fields. Thus, I need something of the following:

public class SessionRecord : IDatabaseEntity<{Guid GameId; Guid PlayerId; DateTimeOffset StartDate}>
{
    public Guid            GameId    { get; set; }
    public Guid            PlayerId  { get; set; }
    public DateTimeOffset  StartTime { get; set; }
    public DateTimeOffset? EndTime   { get; set; }


    public object GetKey() => new { GameId, PlayerId, StartTime }; // Implement the interface
}

Based on this answer, I believe that something like this might be possible, as the compiler can thus differentiate between an 'object' and an anonymous type.

How can I make a method in my interface return an anonymous object, as well as Guids or strings, etc?

1

There are 1 best solutions below

1
Peter On

would it be great to create a model on that like

 public class TestModel {
    public Guid GameId;
    public Guid PlayerId;
    public DateTimeOffset StartDate;
}

and use it like

public class SessionRecord : IDatabaseEntity<TestModel>
{
    public Guid            GameId    { get; set; }
    public Guid            PlayerId  { get; set; }
    public DateTimeOffset  StartTime { get; set; }
    public DateTimeOffset? EndTime   { get; set; }


    public TestModel GetKey() => new TestModel(); // Implement the interface
}

Edit 18:63

public class SessionRecord : IDatabaseEntity<object>
{
    public Guid            GameId    { get; set; }
    public Guid            PlayerId  { get; set; }
    public DateTimeOffset  StartTime { get; set; }
    public DateTimeOffset? EndTime   { get; set; }


    public object GetKey() => new { GameId, PlayerId, StartTime }; // Implement the interface
}