0

Lets see following example:

public Data()
{
   ConnectionString = DefaultConnectionString;
}

public Data(string connectionString)
{
   ConnectionString = connectionString;
}

public string DefaultConnectionString
{
   get
   {
       return System.Configuration.ConfigurationManager.ConnectionStrings["DefaultConnectionString"].ConnectionString;
   }
}

public string ConnectionString { get; set; }

here I am having class which handle sql connection and operations on basis of connection string or by default connection string. And ConnectionString property which logically I am using as readonly i.e. only set from constructor. But in this case property can set from any where else also.
So there is any elegant way to define such property?

Ankush Madankar
  • 3,364
  • 4
  • 34
  • 69
  • private readonly string connectionString; public string ConnectionString { get { return connectionString;}} Set the connectionString field within the constructor... – jmelhus Jun 20 '14 at 07:12
  • I think Heinzi don't understand my question. I know use of private set. – Ankush Madankar Jun 20 '14 at 07:13
  • Why can't you use a readonly field which you set in the constructor and return in the get of the property? – jmelhus Jun 20 '14 at 07:16
  • 2
    What would make a better solution? This is highly readable, and it does exactly what you are asking for. – scheien Jun 20 '14 at 07:27

1 Answers1

3

Make the setter private

public string ConnectionString { get; private set; }

That way the property can only be set privately and read publicly

Mo Patel
  • 2,191
  • 4
  • 21
  • 34
  • Even having private access modifier one can set that property in class itself. But here I want property but set only from Constructor not from else where – Ankush Madankar Jun 20 '14 at 07:08
  • I think setting it the constructor the way you do an adding the private setter should be enough, the property will only be alive for the duration of the object instance and can only be set by other members of the class. As you have control of the flow of the code, just make you don't set it elsewhere. Jon Skeet might hold the answer you are after at this post? http://stackoverflow.com/questions/2480503/is-read-only-auto-implemented-property-possible?rq=1. Why are you trying to achieve this anyway? – Mo Patel Jun 20 '14 at 07:20
  • 1
    @M Patel I think you don't understand my question, I am asking something which is not related to your answer. – Ankush Madankar Jun 20 '14 at 07:25