Search code examples
c#interface

Creating an Instance of an Interface


I have the following interfaces defined:

public interface IAudit {
    DateTime DateCreated { get; set; }
}

public interface IAuditable {
    IAudit Audit { get; set; }
}

The IAuditable interface says which classes I will have an Audit for. The IAudit interface is the actual Audit for that class. For example say I have the following implementations:

public class User : IAuditable {
    public string UserName { get; set; }
    public UserAudit Audit { get; set; }
}

public class UserAudit : IAudit {
    public string UserName { get; set; }
    public DateTime DateCreated { get; set; }

    public UserAdit(User user) {
        UserName = user.UserName;
    }
}

Now given an object which is IAuditable (User from above), I'd like to be able to create an intance of IAudit (UserAdit from above) by feeding in the IAuditable object into the constructor. Ideally i'd have something like:

if (myObject is IAuditable) {
    var audit = new IAudit(myObject) { DateCreated = DateTime.UtcNow }; // This would create a UserAudit using the above example
}

However I have a bunch of problems:

  • You can't create an instance of an interface
  • No where in the code does it define which IAudit applies to which IAuditable
  • I can't specify that the IAudit interface must have a constructor which takes an IAuditable

I'm sure this is a design pattern many have had before but I can't get my head around it. I'd really appreciate if someone could show me how this can be achieved.


Solution

  • No where in the code does it define which IAudit applies to which IAuditable I can't specify that the IAudit interface must have a constructor which takes an IAuditable

    You could fix these two by adding a CreateAudit() function to your IAuditable. Then you'd get an IAudit created from the IAuditable. As a bonus if you wanted to store a reference to the IAudit in the IAuditable (or vice-versa) so you can have them related to each other, it's pretty easy to have an implementing class do that. You could also add GetAuditable() to IAudit to get the IAuditable it was created from, for example.

    Simple implementation would look like this (on a class implementing IAuditable):

    public IAudit CreateAudit()
    {
        UserAudit u = new UserAudit(UserName);
        return u;
    }