views:

316

answers:

2

I need to convert several Java classes to C#, but I have faced few problems.

In Java I have following class hierarchy:

public abstract class AbstractObject {
    public String getId() {
        return id;
    } 
}

public class ConcreteObject extends AbstractObject {
    public void setId(String id) {
        this.id= id;
    }
}

There are implementation of AbstractObject which do not need to have setId() defined, so I cannot move it up in the hierarchy.

How to convert this to C# using properties? Is that possible?

+3  A: 

When you supply only the get portion of a property in .Net, you are explicitly telling the compiler that this property is read-only. It's a bigger deal than just not providing a set. This is evident in the vb version of the property syntax, where you must also explicitly declare the property is ReadOnly.

What you might be able to do is provide both a getter and a setter, but throw a NotImplementedException in the abstract setter, decorate it with the appropriate attributes and document so that no one uses it unless the setter has been property overridden. Otherwise, you're probably better off keeping these as methods anyway, to avoid a disconnect between Java and .Net versions of the code.

Joel Coehoorn
+2  A: 

I would suggest using method calls as you've already outlined to make sure that the usage of the class is clear to the caller. If you're set on implementing it using properties, then you could do the following (some documentation for the new keyword can be found here).

public abstract class AbstractObject {
    protected string id;
    public string Id
    {
        get { return id; }
    }
}

public class ConcreteObject : AbstractObject
{
    public new string Id
    {
        get { return base.Id; }
        set { id = value; }
    }
}
Ant