2

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'

3 Answers 3

5

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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();

Comments

0

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();

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.