Creating an Instance of an Interface
You can't create an instance of an interface
Correct. You create an instance of an object implementing an interface:
IAuditable myUser = new User();
No where in the code does it define which IAudit applies to which IAuditable
You can't do this directly with just one interface. You will need to rethink your design.
You can use a open generic type in the interface and implement it with closed types:
public interface IAudit<T> {
DateTime DateCreated { get; set; }
}
public class UserAudit : IAudit<User> {
public string UserName { get; set; }
public DateTime DateCreated { get; set; }
public UserAdit(User user) {
UserName = user.UserName;
}
}
I can't specify that the IAudit interface must have a constructor which takes an IAuditable
Correct, you can't. See here. You need to create such a constructor on the implementers.
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;
}