mohammad
mohammad

Reputation: 1318

using an interface as constructor parameter

I define an interface and a class like this:

interface ITextBox
    {
        double Left { get; set; }
    }

    class TimeTextBox : ITextBox
    {
        public TimeTextBox(ITextBox d)
        {
            Left = d.Left;
        }
        public double Left { get; set; }
    }

I want to create an instance of this class like this:

ITextBox s;
s.Left = 12;
TimeTextBox T = new TimeTextBox(s);

But this error occure:

Use of unassigned local variable 's'

Upvotes: 2

Views: 127

Answers (3)

ryanscottmurphy
ryanscottmurphy

Reputation: 418

Quoted from: http://msdn.microsoft.com/en-us/library/87d83y5b(v=vs.110).aspx

"An interface contains only the signatures of methods, properties, events or indexers. A class or struct that implements the interface must implement the members of the interface that are specified in the interface definition."

You need a class or struct to implement your interface, and that class or struct needs to be instantiated into an object, then passed into your constructor.

Implementation:

class Example : ITextBox
{
    public double Left { get; set; }
}

Instantiation:

Example s = new Example();

Upvotes: 1

Hans
Hans

Reputation: 2320

ITextBox s; just defines a reference to something that implements ITextBox. It does not define an instance. So on line 2 when you set a property on it the object doesn't exist. The compiler prevents you from making this mistake which is why you get a compiler error.

You need to do ITextBox s = new MyClassThatImplementsITextBox();

Upvotes: 0

Josh
Josh

Reputation: 44906

You haven't instantiated s before trying to use it.

You need to do something like this:

ITextBox s = new SomeClassThatImplementsITextBox();

TimeTextBox t = new TimeTextBox(s);

An interface is just a contract. It only defines structure. You have to have a concrete implementation of a class that implements that interface.

Upvotes: 5

Related Questions