Virtual Properties Problem

  • Thread starter Thread starter SpookyET
  • Start date Start date
S

SpookyET

I have thought that you can disable a set or a get when you override a
virtual property. I guess that I was wrong. The code below compiles and
doesn't throw the exceptions that I have expected. It calls the base
accessor.

using System;

namespace Test
{
public abstract class MetaDataFile
{
protected string name;

public virtual string Name
{
get
{
return name;
}
set
{
name = value;
}
}
}

public class MetaDataFileReader : MetaDataFile
{
public MetaDataFileReader(string name)
{
this.name = name;
}

public override string Name
{
get
{
return name;
}
}
}

public class MetaDataFileWriter : MetaDataFile
{
public override string Name
{
set
{
name = value;
}
}
}

public class Tester
{
public static void Main()
{
MetaDataFile f;
MetaDataFileReader r = new MetaDataFileReader("foobar.torrent");
MetaDataFileWriter w = new MetaDataFileWriter();

r.Name = "test.torrent"; // Should throw a set accessor exception
w.Name = "fooby.torrent";
Console.WriteLine(w.Name); // Should throw a get accessor exception
f = r;
f.Name = "test2.torrent";
}
}
}
 
Spookey,

Virtual only tells you that you can override the default behaviour of
the member,
and if you decide not to then the default (the behaviou found in the base
class) will
be used. When compiled, a property does infact get translated to a pair of
methods
called get_PropertyName and set_PropertyName. This means that when declaring
a virtual property you are infact declaring two virtual methods. In the C#
Language
Specification (10.6.3) you can read the follwing

- A get accessor corresponds to a parameterless method with a return
value of
the property type and the same modifiers as the containing property.

- A set accessor corresponds to a method with a single value parameter
of the
property type, a void return type, and the same modifiers as the
containing property.

HTH,

//Andreas
 
Back
Top