0

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

2 Answers 2

3

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();
    
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.