I have just written a small piece of code and it struck me that I am not sure what method of initialisation is best practice when it comes to initialising my member variables which will be exposed and used via properties. Which is the best way to initialise my member variables out of the two examples below and more importantly why?
Example 1:
private string m_connectionString = ConfigurationManager.ConnectionStrings["ApplicationDefault"].ConnectionString;
private string m_providerName = ConfigurationManager.ConnectionStrings["ApplicationDefault"].ProviderName;
public string ConnectionString
{
get { return m_connectionString; }
set { m_connectionString = value; }
}
public string ProviderName
{
get { return m_providerName; }
set { m_providerName = value; }
}
public EntityClusterRefreshServiceDatabaseWorker()
{
}
Example 2:
private string m_connectionString;
private string m_providerName;
public string ConnectionString
{
get { return m_connectionString; }
set { m_connectionString = value; }
}
public string ProviderName
{
get { return m_providerName; }
set { m_providerName = value; }
}
public EntityClusterRefreshServiceDatabaseWorker()
{
ConnectionString = ConfigurationManager.ConnectionStrings["ApplicationDefault"].ConnectionString;
ProviderName = ConfigurationManager.ConnectionStrings["ApplicationDefault"].ProviderName;
}
NOTE: Assume that I am not using these variables in a static context.
It really doesn't matter which of those you use, except in the very odd situation where a base class constructor calls an overridden member, in which case the timing would change: instance variable initializers are run before the base class constructor call, whereas obviously the constructor body is executed afterwards.
In the latter case, you can make your code a lot simpler though using automatically implemented properties:
public string ConnectionString { get; set; }
public string ProviderName { get; set; }
public EntityClusterRefreshServiceDatabaseWorker()
{
// Code as before
ConnectionString = ...;
ProviderName = ...;
}
You can't do this with the first form, as automatically implemented properties don't have any way of specifying an initial value.
(You may also want to consider making the setters private, but that's a separate concern.)
You are essentially doing the same thing but writing it in a different form.
I always prefer (and use) the second aprroach because I don't like methods being executed in the middle of nowhere. It's better to split things. Attributes are declared on class body and initialized on class constructor.
As long as the connection strings are not supposed to be changed, you can initialize them as static readonly:
private readonly static string m_connectionString = ConfigurationManager.ConnectionStrings["ApplicationDefault"].ConnectionString;
private readonly static string m_providerName = ConfigurationManager.ConnectionStrings["ApplicationDefault"].ProviderName;
readonly variables are allowed to be initialized only in class declaration/contructor and are better optimized for performance than regular private variables.
And back on the question - it really doesn't matter where you'll initialize these.
Drop the fields and go for automatic properties & make your setters private.
public string ConnectionString {get; private set;}
public string ProviderName {get; private set;}
Rob
Related
Here is an interesting tidbit where I could not really find on the interwebs. The idea is that if you have a property such as int a { get; set; } it could set itself.
How do you make the property set itself with int a { get { } set { } }?
What is happening inside of set;?
Here is what I tried to do:
public string Symbol { get { return Symbol; } set { Symbol = value; NotifyPropertyChangedEvent("Symbol"); } }
But it obviously creates a Stack Overflow because it is essentially calling itself over and over.
And I don't want to create 10-20 private variables to work along side of my properties, I want to know what is happening in set;.
Thank you.
set; just creates a private variable that you can't see. You'll need those 10-20 private variables, sorry.
You have to create private variables.
Unfortunately, that's the only way in the specific circumstance you have here.
If you need custom logic, you'll need to provide the backing field yourself:
private string symbol;
public string Symbol
{
get { return symbol; }
set { symbol = value; NotifyPropertyChangedEvent("Symbol"); }
}
And I don't want to create 10-20 private variables to work along side of my properties, I want to know what is happening in set;.
With an automaticaly property (ie: public string Symbol { get; set; }), the compiler creates the backing field automatically. However, there is no way to introduce logic (ie: raise your event) without managing the backing field(s) yourself.
It generates a backing field for you when it gets compiled. You cannot access it via intellisense because it has not been created yet. It is equivalent to the following where '_a' has not been generated yet.
private int _a;
public int a
{
get { return _a; }
set { _a = value; }
}
You could, however, simply set the property itself from inside of your class.
public int a { get; set; }
a = ...;
Additionally, you can set modifiers on the get and set if you only want to be able to set it internally;
public int a { get; private set; }
Can somebody help me understand the get & set?
Why are they needed? I can just make a public variable.
Warning: I am assuming you already know about object-oriented programming.
What are properties?
Properties are language elements that allow you to avoid the repetitive getXYZ() accessors and setXYZ() mutators techniques found in other languages, like Java.
Why do they exist?
They aim to solve the following problems:
Saying get and set in the beginning of every access or mutation of a value is annoying and distracting.
In Java, you often say:
class person
{
private int _age;
public void setAge(int value) { /*check value first, then set _age*/ }
public int getAge() { return this._age; }
}
and then consistently say:
if (person.getAge() > blah || person.getAge() < 10)
{
person.setAge(5);
}
After a while, the get and set become rather annoying.
Providing direct access to the actual variable breaks encapsulation, so that's not an option.
How are they used?
They are used just like variables. You read/write to them just like variables.
How are they created?
They are created as methods. You define a pair of methods that:
Return the current value of the property. Oftentimes, this is nothing more than something like the following:
class Person
{
private int _age; //Declare the backing field
public int Age
{
get { return this._age; }
set { ... }
}
}
Set the value of the property:
class Person
{
public int Age
{
get { ... }
set
{
if (value < 0) //'value' is what the user provided
{ throw new ArgumentOutOfRangeException(); } //Check validity
this._age = value;
}
}
}
Other notes:
Auto-implemented Properties
C# 3.0 introduced auto-implemented properties:
public int Age { get; set; }
This is equivalent to:
private int _age; //The name is auto-generated
public int Age { get { return this._age; } set { this._age = value; } }
Why does it exist?
It helps you avoiding breaking changes in client executables.
Let's say you're lazy and don't want to type the whole thing, and decide to expose a variable publicly. You then create an executable that reads from or writes to that field. Then you change your mind and decide that you in fact needed a property, so you change it to one.
What happens?
The depending executable breaks, because the code is no longer valid.
Auto-implemented properties help you avoid that, without extra redundancy in your initial code.
Indexers
Indexers extend the property syntax to let you index objects (surprise!), just like arrays.
For C++ users: This is similar to overloading operator [].
Example:
private int[] _elements;
public int this[int index] //Indexed property
{
get { return this._elements[index]; }
set
{
//Do any checks on the index and value
this._elements[index] = value;
}
}
You then use them like obj[5] = 10;, which is equivalent to calling the set method of obj's indexer.
In fact, System.Collections.Generic.List<T> is indexed:
var list = new List<int>();
list.Add(10);
list[0] = 5; //You're indexing list, as though it were an array!
Isn't that neat? :)
Anything else?
There are many more features to properties, not all of which are available in C#:
Parametrized properties, of which indexers are a special kind
Getter/setter access modifiers (in C#)
Multiple getters or setters (not in C#)
Et cetera
They are called Accessors
The accessor of a property contains the executable statements associated with getting (reading or computing) or setting (writing) the property. The accessor declarations can contain a get accessor, a set accessor, or both.
The body of the get accessor resembles that of a method. It must return a value of the property type.
http://msdn.microsoft.com/en-us/library/w86s7x04.aspx
private string m_Name; // the name field
public string Name // the Name property
{
get
{
return m_Name;
}
}
The set accessor resembles a method whose return type is void. It uses an implicit parameter called value, whose type is the type of the property.
private m_Name;
public string Name {
get {
return m_Name;
}
set {
m_Name = value;
}
}
Then in the incarnation of C# 3, you can do this much easier through auto-properties
public string Name {get; set; } // read and write
public string Name {get; } // read only
public string Name { get; private set; } //read and parent write
http://msdn.microsoft.com/en-us/library/bb384054.aspx
Properties act as accessors to the internal state of an object, hiding the implementation of that state.
So, for example, you may have a first name property in a class
public class Example
{
private string firstName;
public string FirstName
{
get {return this.firstName;}
}
}
So anyone using the class doesn't need to know how first name is stored, they just know they can get a string representation of it. By adding a set you also add a mutator, something which changes an objects internal state
public class Example
{
private string firstName;
public string FirstName
{
get {return this.firstName;}
set {set this.firstName = value;}
}
}
Again you're still isolating how the first name is stored internally (encapsulation), but users can change it by passing in a string.
Simply put, get and set accessors are the functions called on a Property; that is, when you retrieve the value or when you set it. It forces a type of behavior on the way values are retrieved or set.
For example, you may want to have a mechanism to get/set passwords. Generally speaking, you'll only want to compare the hash of a password instead of storing things plaintext, so you'd have the getter variable retrieve the stored hash, and the setter would take the provided input and hash it for storage.
Here's what I mean:
public class User {
//Usery properties here, and...
private string _password;
public string Password {
get {
return _password;
}
set {
_password = SomeHashingFunction(value);
}
}
}
value is the variable provided to the setter from what has been given in the variable assignment. e.g.: someuser.Password = "blah";
Get and set are used in properties. They can each be public, protected, or private. Similar to accessor and mutator methods, they allow some computation when code tries to access/mutate the property. Of course, as long as you define one of get/set, the other is optional.
Example without properties:
private int test;
public int getTest() {
// some computation on test here, maybe?
return test;
}
private void setTest(int test) {
// some error/range checking, maybe?
this.test = test;
}
With properties:
private int test;
public int Test {
get {
// some computation on test here, maybe?
return test;
}
private set {
// some error/range checking, maybe?
test = value; // value is a keyword here
}
}
get{} and set{} are accessors that offer up the ability to easily read and write to private fields. Working with a simple example:
public class Foo()
{
//Field
private int _bar;
//Property
public int Bar
{
get { return _bar; }
set { _bar = value; }
//value is an implicit parameter to the set acccessor.
//When you perform an assignment to the property, the value you
//assign is the value in "value"
}
}
In this case, Bar is a public property that has a getter and a setter that allows access to the private field _bar that would otherwise be inaccessible beyond class Foo.
Now in a class that has an instace of Foo, you can do this:
public class IHasAFoo()
{
private Foo _myFoo = new Foo();
public void SomeMethod()
{
_myFoo.Bar = 42;
}
}
So the public accessor allows you to set the value of the private field back in Foo.
Hope that helps!
When defining classes I expose class members as properties along the lines of :
class ClassA
{
private String _Name;
public String Name
{
get { return _Name; }
set { _Name = value; }
}
}
What is best practice for dealing with collections within classes, with respect to accessors
So if the class is extended to something like :
class ClassA
{
private String _Name;
private List<String> _Parts = new List<String>();
public String Name
{
get { return _Name; }
set { _Name = value; }
}
}
How do I expose the next item?
Expose a read-only instance of the collection. Note that the contents are not read-only, but the reference is.
public IList<String> Parts { get; private set; }
The naming conventions I've come across recommend
private String _name;
Also you could use automatic properties which generate the same code you've written
public string Name {get; set;}
For collections, I don't like to expose the actual collection but methods to work on it.
public void Add(...
public void Remove(...
Otherwise you could make it readonly with an automatic property
public IList<string> Parts {get; private set;}
I don't know if there is specifically a best practice in place, but there are a couple things to consider. The basic approach is the same as what others have stated:
public List<String> Parts
{
get { return _Parts; }
private set { _Parts = value; }
}
The important point here is to make sure that _Parts is never null. That leads to subtle and hard to discover bugs.
However, if you need to send events when elements are added and removed you have only two options:
Use a subclass of List that sends the events when appropriate
Don't expose the List at all, and merely expose the AddPart(), RemovePart(), and ListParts() (that returns a copy of the current list).
If your needs are simple, just expose the property (but protect it from being assigned null). Otherwise you'll have to be a bit more fancy.
It depends on how serious you are about encapsulating the way the data is stored. If you're doing a lightweight class and you are just providing the storage but want to leave the accessing decisions completely up to the consumer of your class, you just expose it like a standard property or make it an auto-property.
public List<String> Parts { get; private set; }
If you want to ensure the variable is never null, continue to use your private backing field and add checks.
private List<String> _Parts;
public IList<String> Parts
{
get
{
if (_Parts == null)
_Parts = new List<String>();
return _Parts;
}
private set
{
if (value != null)
_Parts = value;
}
}
If, however, you want to control synchronization, or anything else of that sort, you'd expose methods that are logical for what you're doing.
public void AddPart(String part);
public void RemovePart(String part);
public String GetPart(int index);
public IEnumerable<String> GetAllParts()
{
foreach(String part in _Parts)
yield return part;
}
Couldn't you just do the same - but for the list?
public List<String> parts
{
get { return _Parts; }
set { _Parts = value; }
}
I would expose as property as well
public List<string> Parts { get; set; }
You have a bunch of options and it really depends on what kind of operations you want to open up to the public API of your class. The most common approaches are:
Provide a readonly property to returns the actual collection instance with the same type information.
Provide a readonly property that returns an IEnumerable interface.
Provide a readonly property that returns a ReadOnlyCollection wrapper of the collection.
Again, it really depends on how you want to expose the collection, but the 3 options above will work fine in most scenarios. If you have more specialized requirements like allowing additions to the collection from the public API while at the same time disallowing removals then things get a bit more complicated.
We typically do the following:
private Collection<String> _parts = new Collection<String>();
public Collection<String> Parts {
get { return _parts; }
}
This ensures that the collection is instantiated when the object is created and it makes the underlying reference for the _parts collection read only. Which means you can add/remove parts but you can't change what the property points to.
I've created this "question" as a community-wiki, because there is no right or wrong answer. I only would like to know how the community feels about this specific issue.
When you have a class with instance variables, and you also created properties that are simply getters and setters for these instance variables, should you use the properties inside your own class, or should you always use the instance variable?
Having auto-properties in C# 3.0 made this an even harder decision.
Using properties:
public class MyClass
{
private string _name;
// could be an auto-property of-course
public string Name { get { return _name; } set { _name = value; } }
public void Action()
{
string localVar = Name;
// ...
Name = "someValue";
// ...
}
}
Using instance variables:
public class MyClass
{
private string _name;
public string Name { get { return _name; } set { _name = value; } }
public void Action()
{
string localVar = _name;
// ...
_name = "someValue";
// ...
}
}
(for those who hate member prefixes, I apologize)
Personally, I always use the latter (instance variables), because I feel that properties should only be used by other classes, not yourself. That's why I mostly stay away from auto-properties as well.
Of course, things change when the property setter (or getter) does a little more than just wrapping the instance variable.
Are there compelling reasons to pick one or the other?
I always use instance variables as well. The reason is because properties might be doing stuff like validating arguments (like in a setter) for not null or not empty. If you're using the variable inside your class code, there's no need to go through the extra overhead of those checks (assuming you know the variable value is valid). The properties could be doing other things as well (logging, for example), that are important for the public API, but not for internal usage, so again, it's better to avoid the overhead and just use the instance variable in my opinion.
I think it becomes more difficult to change the internal implementation if the code uses its own public interface.
Difficult to explain but consider these expressions:
mTotalPrice = mPrice * mQuantity;
mTotalPrice = Price * Quantity;
What to do in the second expression if I need to change the internals to express all prices in € instead of $ (without affecting the public interface which still uses $)?
One solution is to make the expression more complex by adding the opposite of the change in the property.
mTotalPrice = Price / Rate * Quantity
The other solution is to start to use the private field instead.
mTotalPrice = mPrice * Quantity
In the end you get a mix of private and public use. The only way to get consistent use is to always use the private field.
I don't like prefixing members either, but actually I find I can write something like this accidently and not spot it until run time. Which kinda tempts me to avoid using properties where they're not necessary... but I still do, currently!
Public String MyString
{
{ get { return this.MyString; } } //<== Stack Overflow
{ set { this.myString = value; } }
}
private String myString;
I think that there is no difference between these two approaches.
Auto-implemented properties is just a quick way to access private members which are created any way.
Example from MSDN:
class Customer
{
// Auto-Impl Properties for trivial get and set
public double TotalPurchases { get; set; }
public string Name { get; set; }
public int CustomerID { get; set; }
// Constructor
public Customer(double purchases, string name, int ID)
{
TotalPurchases = purchases;
Name = name;
CustomerID = ID;
}
// Methods
public string GetContactInfo() {return "ContactInfo";}
public string GetTransactionHistory() {return "History";}
// .. Additional methods, events, etc.
}
99% of the time I use the property rather then the instance variable. In the past, I've worked with a lot of code that used the instance variable and when there was a bug associated with that variable, I had to put a breakpoint on every line of code that referenced it.
I decided to use properties instead, either public or private, to wrap around the instance variable. Doing this means that I only have to put a breakpoint in the getter/setter of the property if I need to debug an issue with the instance variable, rather then having (potentially) a lot of breakpoints scattered all over the code.
I have a class in test.cs in which I have a string value string user="testuser". I want to use the test.cs's user value in another class. How can I do this?
Declare the string public:
public string user = "testuser";
Then you can access it from another class via
Test.user
However, depending on what exactly you want, you should perhaps make the field read-only:
public readonly string user = "testuser";
Or use a property, bound to a backing field:
public string User
{
get { return this.user; }
}
In fact, properties are the canonical way of making information accessible from the outside except for very few, very special cases. Public fields are generally not recommended.
As Ant mentioned in a comment, there is also the option of making it a constant (assuming it is, in fact, a constant value):
public const string user = "testuser";
Make a public property.
Public string TestUser
{
get { return testUser;}
}
You should make a property of user and expose this to any other class that want to read or write it's value.
class MyClass
{
private static string user;
public static string User
{
get { return user; }
set { user = value; }
}
}
class MyOtherClass
{
public string GetUserFromMyClass()
{
return MyClass.User;
}
}
public class AClass
{
// declarations
private string _user = "testUser";
// properties
public string User { get { return this._user;} set { this._user = value; } }
}
then call your class property, e.g.
AClass myClass = new AClass();
string sYak = myClass.User;
As suggested in the earlier answers, making "user" into a Property is the ideal technique of accomplishing this. However, if you want to expose it directly anyhow, you should use static to avoid having to instantiate an object of that class. In addition, if you don't want the demo class to manipulate the value of user, you should declare is readonly as well, like below
public static readonly user="text user";