Question

Consider the below:

public class Project.Model.ModelName : BaseClass
{
    private int _id;
    private string _name;

    public int ID
    {
        get { return _id; }
        set { _id = value; }
    }

    public string Name
    {
        get { return _name; }
    }
}

public class Project.BLL.ModelName
{
    public static string ComputeName(Model.ModelName m)
    {
        // Determine value using complex business logic

        return "Whatever";
    }

    public static bool SetName(Model.ModelName m)
    {
        string Name = ComputeName(m);

        // How can I set the ModelName.Name value here?
        m.Name = ??? // No set accessor
    }
}

I have a model with a string property that only has a get accessor, we do not want the value to be set directly.

The value for the property is computed in the BLL, a different library.

What's the best way to set the value of the property without using reflection?

For clarification, the challenge is that the Name value needs to be immutable. The same model is frequently accessed and modified. We did not want to risk someone assigning a value to it after the fact. I guess I'm looking for a best practice to maintain immutability.

Was it helpful?

Solution

ModelName.Name property only have a getter specified on _name. There is no way you it can be altered as it is. The only way to do it while preventing the other to do the same is through access modifier.

If Project.BLL and Project.Model is within the same assembly, you can use the internal modifier to restrict the access from other assembly. or apply a [assembly: InternalsVisibleTo("Project.BLL")] on Project.Model.ModelName

 //1. Add a setter on the property, or : 
public string Name
{
    get { return _name; }
    internal set { _name = value; }
}

//2. Add a setter method for _name :
internal void SetName(string value)
{
    _name = value;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top