user572844
user572844

Reputation:

Problem with interface

What is bad on this code? It is simple example:

class Program
{
    public interface IAccount
    {

    }

    public class Account :IAccount
    {

    }

    public static IAccount LogOn()
    {
        return new Account();
    }

    public class Avatar
    {
        public Account Cred { get; set; }
    }


    static void Main(string[] args)
    {
        var avatar = new Avatar();

        avatar.Cred = LogOn();
    }
}

I get compile error :

    Error   5   Cannot implicitly convert type 'console.Program.IAccount' to 'console.Program.Account'. An explicit conversion exists (are you missing a cast?) C:\Users\Jan\Documents\Visual Studio 2010\Projects\BACKUP\Pokec_Messenger\ver.beta
\Pokec__Messenger\console\Program.cs    35  27  console

What is it correct implementation. Thank for advice

Upvotes: 0

Views: 89

Answers (2)

Jon Skeet
Jon Skeet

Reputation: 1503280

Your Avatar.Cred property is of type Account, not IAccount... but LogOn is declared to return just IAccount. So it could return some other IAccount implementation - the compiler won't let you just assume that the IAccount will be an Account without an explicit cast.

Options:

  • Change the type of the Cred property to IAccount instead of Account. This is probably best as it reduces the coupling between Avatar and Account, so you can use other implementations of IAccount.
  • Change the return type of LogOn to Account instead of IAccount. This ties the LogOn API to Account, instead of just the implementation.
  • Cast when you assign the property:

    avatar.Cred = (Account) LogOn();
    

Upvotes: 3

spender
spender

Reputation: 120518

public class Avatar
{
    public IAccount Cred { get; set; }
}

Upvotes: 2

Related Questions