user848682
user848682

Reputation: 389

How to use C# interface properly?

Can someone correct my code? I want to create an interface object and use it methods but Im stuck with this code..

Visual Studio Error prompt : Use of unassigned local variable 'MyInterface'

IBattleNetSettings MyInterface;
        MyInterface.Username = "MyUsername";
        BattleNetClient cs = new BattleNetClient(MyInterface); 

btw , if you want the interface class here's the code: IBattleNetSettings

and for the BattleNetClient class : BattleNetClient <-- Take a look at this code.Its constructor requires an instance of IBattleNetSettings interface.

I just want to create an instance of BattleNetClient class but Im stucked since It requires an instance from IBattleNetSettings and I dont know how to do it.

How can I create instance of BattleNetClient class?

Thanks in Advance : )

Upvotes: 1

Views: 384

Answers (2)

Arafangion
Arafangion

Reputation: 11950

Consider assigning to it?

An interface is just that... An interface. You will want to use a concrete implementation.

For example, you may wish to use a class named BattleNetSettings which implements IBattleNetSettings, you can use:

IBattleNetSettings MyInterface = new BattleNetSettings();
MyInterface.Username = "MyUsername";
BattleNetClient cs = new BattleNetClient(MyInterface);

However, the use of the name "MyInterface" is very confusing, I suggest using a more appropriate name. :)

Upvotes: 2

Mark Byers
Mark Byers

Reputation: 839044

You can't create instances of interfaces. You should create (or otherwise obtain) an instance of a class that implements that interface:

IBattleNetSettings settings = new BattleNetSettings();

If the project doesn't provide an implementation you can use then you may have to write one yourself:

public class BattleNetSettings : IBattleNetSettings 
{
    public string Username { get; set; }
    // etc...
}

Upvotes: 4

Related Questions