Read Only Property in Interface

G

Guest

I decleared interface with read only property
interface IPersonName
{
string Name { get; }
}

and in implementation of this interface, i implemented as read/write property

classs Student : IPersonName
{
string _name;
public sting Name
{
get { return _name; }
set ( _name = value; }
}
}

this code compiled successfully, Why?
 
G

Guest

But in interface property is declared as Read Only and implemented as
Read/Write property.

Looking for reson why its allowed
 
J

Jared Parsons [MSFT]

The interface isn't spec'd as read only per say. A better way to think
about it is that it is a property that at least must provide read access.
Remember that under the hood, properties are beautiful wrappers over get and
set methods. So really an interface as you described isn't much different
than the following.

interface IPersonName
{
string get_Name();
}
 
H

Helge Jensen

Deepak said:
I decleared interface with read only property
and in implementation of this interface, i implemented as read/write property

classs Student : IPersonName
{
string _name;
public sting Name
{
get { return _name; }
set ( _name = value; }
}
}

You could simply do:

class Student: IPersonName {
public string Name;
IPersonName.Name string Name { get { return this.Name; } }
}

Which would allow direct access to Name in the cases where the static
type of the object is known to be Student, not only IPersonName.
this code compiled successfully, Why?

Because having "set" doesn't violate the interface, which just declares
that you must have "get".

You cannot call the "set" from code which only knows the instance as
IPersonName:

Studer s = new Student();
s.Name = "foo"; // ok
IPersonName n = s;
n.Name = "foo"; // compiler-error
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top