Search code examples
c#classpropertiesimmutability

How to add a property to represent a sample name that may not be changed once initialized?


I am trying to make a property in my class. What would I need to do where once the property is initialized, it cannot be changed?

These are the actual instructions:

Create a class in the existing namespace, either in an existing code file or in a new file, to represent the amount in pounds of dirt sample. In this class (a) do not create constructors. (b) inherit the sand class (to make use of the sand property). (c) add a property to represent the sample name. This property may not be changed once initialized. (d) add a property to represent and process assignments the quantity of clay, with a minimum value of 0. (e) add methods to return the weight of the sample, the percentage of sand in the sample and the percentage of clay in the sample.

I am on part (c). I have tried to exclude setters. Then, I've tried to use readonly, but it cannot work because my class cannot have constructors.

public class AmountSand //parent class
    {
    public class AmountSand {
 private double quantity;
 public double Sand {

  get {
   return quantity;
  }
  set {
   if (value >= 0) quantity = value;
  }
 }
}

public class AmountDirt: AmountSand { //part (b): inherited the parent class, AmountSand
  private string name = null;
  private double clay;

  public string Name { //here is where the specific property starts
   get {
    return name;
   }
   set {
    if (name == null)
     name = value;
   }
  } //ends

  public double Clay {
   get {
    return clay;
   }
   set {
    if (value >= 0) clay = value;
   }
  }

Solution

  • Depends on from where you would like it to be initialized.

    EDIT: sorry, i didn't read that your class could have ctors, but i'll keep this in for completeness. It seems kinda weird that your class can't have ctors. May I ask why?

    From the ctor:

    class MyClass
    {
        public MyClass()
        {
            Name = "Muhammed";
        }
    
        public MyClass(string newName)
        {
            Name = newName;
        }
    
        public string Name{get;}
    }
    

    If you'd like it to be initialized from outside the class, your code is not too far off. You could even remove the backing property. I'd use

    if(string.IsNullOrEmpty(Name))
    

    rather than comparing to null.

    if you'd like it to be set from a method inside your class:

    public string Name{get; private set;}