Rectangle 27 0

c Creating an Instance of an Interface?


IAuditable myUser = new User();
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;
    }
}

Correct, you can't. See here. You need to create such a constructor on the implementers.

Correct. You create an instance of an object implementing an interface:

I can't specify that the IAudit interface must have a constructor which takes an IAuditable

No where in the code does it define which IAudit applies to which IAuditable

Useful answer, useful info for OP, but still focuses too much on the c#/.net specifics to get an upvote from me ... for now. Tridus' addresses the real issue IMO. Still, useful info for OP.

You can use a open generic type in the interface and implement it with closed types:

You can't create an instance of an interface

You can't do this directly with just one interface. You will need to rethink your design.

Note
Rectangle 27 0

c Creating an Instance of an Interface?


IAuditable j = ((IAuditable)Activator.CreateInstance(myObject.GetType()));

Alternatively you could research something called 'Dependancy Injection' which allows you to specify which type of concrete class to "inject" into parameters that call out interfaces in constructors, or in fields. I'm not sure your total design, so this might be applicable. In Dependancy Injection you can state in your code IAuditables should be created using UserAudit, although there's a little more wireup than simply calling "new IAuditable"

Obviously you cannot create an instance of an interface, but if you were really trying to create an instance of the passed in class you could do this:

You need to know which concrete class to construct and in your example the only option is myObject.

Note