tags:

views:

34

answers:

3

I'm currently implementing a poor-man's version of the RSA Algorithm and I wanted the prime numbers d, e, m, and n to be read-only as they will be automatically generated within ithe constructor body. However, I get two different results when I type:

class RSA
{
    public RSA() 
    {
        n = 4;
    }

    private long n { get; private set; }
}

or

class RSA
{
    public RSA() 
    {
        n = 4;
    }

    private long n { get; }
}

Reading the book Accelarated C#, I got the impression that a private set function can be implemented with auto-implemented properties. Turns out I can do it in the constructor itself too, but only for the first version.

Reading the C# 3.0 standard it says:

A property that has both a get accessor and a set accessor is a read-write property, a property that has only a get accessor is a read-only property, and a property that has only a set accessor is a write-only property.

Yet they don't behave equally.

Simple question: Why can I initialize the value in my constructor when I explicitly declare private set, but not if I do it implicitly? What are the differences here?

+1  A: 

In the first case the setter is private. This means that you can set the value of this property everywhere from inside this class not only in the constructor. In the second example there's no setter won't be able to set the value. Using readonly field is probably most correct semantically in your case as it will allow you to set its value either in the constructor or directly when declaring the field (if this field shouldn't be visible from outside of this class):

class RSA
{
    public RSA() 
    {
        n = 4;
    }

    private readonly long n;
}
Darin Dimitrov
+1  A: 

There's no such thing as an implicit autogenerated private setter. If you omit set;, you cannot assign it a value, which will not compile because it can never be assigned.

Additionally, by making n private you cannot access it from outside that class. If that is your intention, there's no point in using a property at all. You can simply declare it as a field: private readonly long n;

Richard Szalay
+1  A: 

If you really want a property with a readonly value, you could use a Property with the explicit backing field IE:

public class RSA {
  private readonly long _n;
  public long n {
    get { return _n; }
  }

  public RSA() 
  {
     _n = 4;
  }
}
Tejo