Converting Java to C #

I need to convert several Java classes to C #, but I ran into several problems.

In Java, I have the 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 is an AbstractObject implementation for which there is no need to define setId (), so I cannot move it in the hierarchy.

How do I convert this in C # using properties? Is it possible?

0


source to share


2 answers


I would suggest using method calls as you already pointed out to make sure the use of the class is clear to the caller. If you've configured it to use it using properties, you can do the following (you can find some documentation for the new keyword 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; }
    }
}

      

+2


source


When you only provide a subset of a get

property in .Net, you are explicitly telling the compiler that the property is read-only. This is a bigger deal than just absence set

. This is seen in the vb version of the property syntax where you must also explicitly declare the ReadOnly property.



What you could do is provide both a getter and a setter, but cast a NotImplementedException

in the abstract setter, decorate it with the appropriate attributes and document so that nobody will use it unless the setter was property overridden. Otherwise, you are probably better off not using these methods to avoid the gap between Java and .NET versions of code.

+3


source







All Articles