UnitTesting Properties in .Net? - c#

I am working on a lib that I want to release in open source. I have started writing the tests for the code, and I was wondering how I am suppose to test a property in a .Net object. Lets say I have the following:
public class Person{
#region variables
private string _name = String.Empty;
private string _surname = String.Empty;
#region properties
public string Name{
get{
return _name;
}
}
public string Surname{
get{
return _surname;
}
set{
_surname = value;
}
}
}
I have two questions related to the code:
How do I Unit test a Property that just has a getter (Like Name in the example)
How do I Unit test a Property with a setter and a getter (Like Surname in the example)
I want to test properties that are that simple because I have already found errors in other code were Itellinsense did the wrong autocomplete and the property was not returning the correct variable.
Update: I am not talking about simple properties as the one in the example, they do have some logic behind them and are quite hard to debug. Writing a test that uses the setter to test the getter and vice versa is not good because if there is a fail I won't know which method to blame. I am using properties because they were added as public variables and later more logic had to be added.

Don's waste your time on writing silly
tests for getters and setters.
Another test will probably set the
Name and then get that property so you
will have code coverage for the
getter.
You should test anything public facing, including properties. If you don't test a property, you run the risk that someone may add some logic inside it, breaking the functionality.
Also you shouldn't rely on it being tested in other tests. This makes your tests brittle, and makes it harder to identify where the problem is as a test will be testing more than one thing.

How do I Unit test a Property that
just has a getter (Like Name in the
example)
Really not so different from testing if you had a setter. you'll just need to find another way of determining the output. Could be in a ctor, or the result of other setters/operations on the object.
[Test]
public void NamePropTest()
{
Person p = new Person();
//Some code here that will set up the Person object
// so that you know what the name will be
Assert.AreEqual("some known value...", p.Name);
}
If we had setters for Name and SurName, but only a getter for FullName, the test could look like this:
[Test]
public void NamePropTest()
{
Person p = new Person();
p.Name = "Sean";
p.Surname = "Penn";
Assert.AreEqual("Sean Penn", p.FullName);
}

You should test properties. Also automatic properties!
Unittests are about assuring that changes to the program, don't break the program.
You could end up changing a property implementation at some time, and you want to make sure the program still works as expected. You do that with your tests.
Even if you use automatic properties (as a replacement for fields/member variables), the reason for making them properties is in case you want to change their implementation later on. Then you'll want the tests to be there.
EDIT: (In response to shahkalpesh's comment...)
If you are changing the
implementation, the tests might also
require the change. So, I don't know
of why someone should test simple
get/set?
Starting with this class:
public class TimeOfDay
{
public int Hour{get; private set;}
public int Minute{get; private set;}
public TimeOfDay(int hour, int minute)
{
Hour = hour;
Minute = minute;
}
}
When changing the implementation, the tests are still valid!
public class TimeOfDay
{
public int _minutesSinceMidnight = 0;
public int Hour
{
get { return _minutesSinceMidnight / 60; }
set { _minutesSinceMidnight = value * 60 + Minutes; }
}
public int Minute
{
get { return _minutesSinceMidnight % 60; }
set { _minutesSinceMidnight = Hour * 60 + value; }
}
public TimeOfDay(int hour, int minute)
{
Hour = hour;
Minute = minute;
}
}
Throw in some date and time arithmetic functions or something, and I would like the tests to show that everything still works...

I think you should test, them if you write them like you did. Afterall you can mistype something.
Just something like
var person = New Person();
person.Surname = "test";
Assert.AreEqual("test", person.Surname);
After all TDD and unit testing n general is all about avoiding the most bugs you can.
If by accident you had written this.
public class Person{
#region variables
private string _name = String.Empty;
private string _surname = String.Empty;
#region properties
public string Name{
get{
return _name;
}
}
public string Surname{
get{
return _name;
}
set{
_name = value;
}
}
}
then you would have a bug.
Testing the automatic properties is perhaps less valuable. But that's another question.

Those property should be there because you have usages that needs them. As for these there should be unit tests, you should already have coverage for them.
If there is no scenario that needs them, they possibly shouldn't be there at all.

As I understand, you shouldn't be testing properties (i.e. those which are simple get/set).
I am not sure what version of c# you are using. But, you can use automatic properties to avoid the simple set/get problems that you are facing.
See this link

Don's waste your time on writing silly tests for getters and setters.
Another test will probably set the Name and then get that property so you will have code coverage for the getter.

My question is more related of HOW to
write the test. I have been thinking
about it and I need to access the
private values to make sure that the
properties work as expected, otherwise
I do not know how to do it.
https://stackoverflow.com/users/59332/mandel
Ok...since you insist on knowing how to do it....
[Test]
TestMethod()
{
Person p = new Person();
p.Name = "a name";
p.Surname = "a surname";
Assert.That(p.Name, Is.EqualTo("a name"));
Assert.That(p.Surname, Is.EqualTo("a surname"));
}
However, that only works if you have setters....
If you only have getters there are only two ways I can think of that you can do this.
know the return value in advance and assert against that.
Use Reflection to set the value and then assert against that known value.
A better bit of advice would be to give up and test something worthwhile that actually adds value to your software. Testing getters and setters is an absolute waste of time unless there is something complex going on behind them....which is rarely the case.

I think you meant that your getter-only propoerty uses private fields or other private data. If you need to set them, only way is to get them by Reflection (see all (something)Info classes in System.Reflection). But there is a hard discussion if this is a good practice.

Related

Object Oriented - Class Variables

I am pretty new to OOP and looking into things in a bit more depth, but I have a bit of confusion between these 3 methods in C# and which one is best and what the differences are between 2 of them.
Example 1
So lets start with this one, which (so I understand) is the wrong way to do it:
public class MyClass
{
public string myAttribute;
}
and in this way I can set the attribute directly using:
myObject.myAttribute = "something";
Example 2
The next way I have seen and that seems to be recomended is this:
public class MyClass
{
public string myAttribute { get; set;}
}
With getters and setters, this where I dont understand the difference between the first 2 as the variable can still be set directly on the object?
Example 3
The third way, and the way that I understand the theory behind, is creating a set function
public class MyClass
{
string myAttribute;
public void setAttribute(string newSetting)
{
myAttribute = newSetting;
//obviously you can apply some logic in here to remove unwanted characters or validate etc.
}
}
So, what are the differences between the three? I assume example 1 is a big no-no so which is best out of 2 and 3, and why use one over the other?
Thanks
The second
public class MyClass
{
public string MyAttribute { get; set;}
}
is basically shorthand for:
public class MyClass
{
private string myPrivateAttribute;
public string MyAttribute
{
get {return myPrivateAttribute;}
set {myPrivateAttribute = value;}
}
}
That is an auto-implemented property, which is exactly the same as any regular property, you just do not have to implement it, when the compiler can do that for you.
So, what is a property? It's nothing more than a couple of methods, coupled with a name. I could do:
public class MyClass
{
private string myPrivateAttribute;
public string GetMyAttribute()
{
return myPrivateAttribute;
}
public void SetMyAttribute(string value)
{
myPrivateAttribute = value;
}
}
but then instead of writing
myClass.MyAttribute = "something";
string variable = myClass.MyAttribute;
I would have to use the more verbose, but not necessarily clearer form:
myClass.SetMyAttribute("something");
string variable = myClass.GetMyAttribute();
Note that nothing constraints the contents of the get and set methods (accessors in C# terminology), they are methods, just like any other. You can add as much or as little logic as you need inside them. I.e. it is useful to make a prototype with auto-implemented properties, and later to add any necessary logic (e.g. log property access, or add lazy initalization) with an explicit implementation.
What your asking here has to do with encapsulation in OOP languages.
The difference between them is in the way you can access the propriety of an object after you created an object from your class.
In the fist example you can access it directly new MyClass().MyAttribute whether you get or set it's value.
In the second example you declare 2 basic functions for accessing it:
public string MyAttribute
{
get {return myPrivateAttribute;}
set {myPrivateAttribute = value;}
}
In the third example you declare your own method for setting the value. This is useful if you want to customize the setter. For example you don't want to set the value passed, but the value multiplied by 2 or something else...
I recommend some reading. You can find something here and here.
Property is a syntactic sugar over private attribute with get and set methods and it's realy helpful and fast to type;
You may treat automatic property with { get; set;} as a public attribute. It has no additional logic but you may add it later without uset ever notice it.
Just exchange
public string MyLine { get; set;}
to
string myLine;
public string MyLine
{
get { return myLine; }
set { myLine = value + Environment.NewLine; }
}
for example if you need so.
You can also easily create read only property as { get; private set }.
So use Properties instead of public attributes every time just because its easier and faster to write and it's provides better encapsulation because user should not be used get and set methods if you decide to use it in new version of yours programm.
One of the main principles of OOP is encapsulation, and this is essentially the difference between the first example and the other 2.
The first example you have a private field which is exposed directly from the object - this is bad because you are allowing mutation of internal data from outside the object and therefore have no control over it.
The other 2 examples are syntactically equivalent, the second being recommended simply because it's less code to write. However, more importantly they both restrict access & control mutation of the internal data so give you complete control over how the data should be managed - this is ecapsulation.

Setting variables in constructor vs definition

Observe the following...
//pattern 1
public class Cheesesteak
{
public string bread {get; private set}
public string cheese {get; private set}
public Cheesesteak()
{
bread = "Amoroso";
cheese = "Cheez Whiz";
}
}
//pattern 2
public class Cheesesteak
{
public string bread
{
get {return bread;}
set
{
bread = "Amoroso";
}
}
public string cheese
{
get {return cheese;}
set
{
cheese = "Cheez Whiz";
}
}
public Cheesesteak() {}
}
This is a curiosity question. Is there any advantage or particular reason that you would set the variables in the definition of the "set" versus declaring them in the constructor? My initial guess is pattern 1 is shorter, but less efficient during compile.
Is there any advantage or particular reason that you would set the variables in the definition of the "set" versus declaring them in the constructor?
No, and in fact, this is probably not what you want at all. This will make it impossible to set "break" or "cheese", as any call, such as bread = "rye";, would set it to "Amoroso" (if it worked, but will cause a StackOverflowException). Also note that trying to retrieve the value in your code will cause a StackOverflowException, and the property getter returns the property and not a backing field value.
You were likely thinking of this:
public class Cheesesteak
{
private string bread = "Amoroso";
public string Bread
{
get {return bread;}
set
{
bread = value;
}
}
// ...
The only advantage here is you're setting the "default" value where the field is defined, which can help with maintainability or readability in some cases, and even potentially eliminate the need for a defined constructor, which might reduce the overall length of code.
My initial guess is pattern 1 is shorter, but less efficient during compile.
In general, setting the fields inline vs. setting them in a constructor does not make this less efficient. The compiler will cause the type's actual constructor to set the fields first then run the constructor code, so both versions end up (for practical purposes) the same in terms of the compiled IL. This isn't a matter of efficiency, but rather of code readability and maintainability.
Note that, if you wanted the property to always be a constant (ie: Bread should always return "Amoroso"), you can just make the property have a getter and no setter:
public string Bread { get { return "Amoroso"; } }
I suspect this is not the case, but I thought I'd mention it as an option just in case it's what you intended.
Well the second option will result in a StackOverflowException whenever a user tries to assign or access the properties, versus the first which will only allow private access to them.
You maybe meant something like:
private string bread = "Amaroso";
public string Bread
{
get { return bread; }
private set
{
bread = value;
}
}
Which will initialize the property with "Amaroso" but will not allow it to be set publicly.
No, they are completely different. The get and set blocks are actually methods that get executed when the property is read from or written to. Nether of them have anything to do with initialization.
var x = thing.Property; // Property's "get" accessor method is executed
thing.Property = x; // Property's "set" accessor method is executed
In your second example, both property accessors will infinitely recurse on themselves and you will get a StackOverflowException.

Getters, setters, and properties best practices. Java vs. C#

I'm taking a C# class right now and I'm trying to find out the best way of doing things. I come from a Java background and so I'm only familiar with Java best-practices; I'm a C# novice!
In Java if I have a private property, I do this;
private String name;
public void setName(String name) {
this.name = name;
}
public String getName() {
return this.name;
}
In C#, I see that there are many ways of doing this.
I can do it like Java:
private string name;
public void setName(string name) {
this.name = name;
}
public string getName() {
return this.name;
}
Or I can do it this way:
private string name;
public string Name {
get { return name; }
set { name = value; }
}
Or:
public string Name { get; set; }
Which one should I use, and what are the caveats or subtleties involved with each approach? When creating classes, I am following general best-practices that I know from Java (especially reading Effective Java). So for example, I am favoring immutability (providing setters only when necessary). I'm just curious to see how these practices fit in with the various ways of providing setters and getters in C#; essentially, how would I translate best-practices from the Java world into C#?
EDIT
I was posting this as a comment to Jon Skeet's answer but then it got long:
What about a non-trivial property (i.e., with significant processing and validation perhaps)? Could I still expose it via a public property but with the logic encapsulated in get and set? Why would/should I do this over having dedicated setter and getter methods (with associated processing and validation logic).
Pre-C# 6
I'd use the last of these, for a trivial property. Note that I'd call this a public property as both the getters and setters are public.
Immutability is a bit of a pain with automatically implemented properties - you can't write an auto-property which only has a getter; the closest you can come is:
public string Foo { get; private set; }
which isn't really immutable... just immutable outside your class. So you may wish to use a real read-only property instead:
private readonly string foo;
public string Foo { get { return foo; } }
You definitely don't want to write getName() and setName(). In some cases it makes sense to write Get/Set methods rather than using properties, particularly if they could be expensive and you wish to emphasize that. However, you'd want to follow the .NET naming convention of PascalCase for methods, and you wouldn't want a trivial property like this to be implemented with normal methods anyway - a property is much more idiomatic here.
C# 6
Hooray, we finally have proper read-only automatically implemented properties:
// This can only be assigned to within the constructor
public string Foo { get; }
Likewise for read-only properties which do need to do some work, you can use member-bodied properties:
public double Area => height * width;
If all you need is a variable to store some data:
public string Name { get; set; }
Want to make it appear read-only?
public string Name { get; private set; }
Or even better...
private readonly string _name;
...
public string Name { get { return _name; } }
Want to do some value checking before assigning the property?
public string Name
{
get { return m_name; }
set
{
if (value == null)
throw new ArgumentNullException("value");
m_name = value;
}
}
In general, the GetXyz() and SetXyz() are only used in certain cases, and you just have to use your gut on when it feels right. In general, I would say that I expect most get/set properties to not contain a lot of logic and have very few, if any, unexpected side effects. If reading a property value requires invoking a service or getting input from a user in order to build the object that I'm requesting, then I would wrap it into a method, and call it something like BuildXyz(), rather than GetXyz().
Use properties in C#, not get/set methods. They are there for your convenience and it is idiomatic.
As for your two C# examples, one is simply syntactic sugar for the other. Use the auto property if all you need is a simple wrapper around an instance variable, use the full version when you need to add logic in the getter and/or setter.
In C# favor properties for exposing private fields for get and/or set. The thie form you mention is an autoproperty where the get and set automatically generate a hidden pivot backing field for you.
I favor auto properties when possible but you should never do a set/get method pair in C#.
public string Name { get; set; }
This is simply a auto-implemented property, and is technically the same as a normal property. A backing field will be created when compiling.
All properties are eventually converted to functions, so the actual compiled implementation in the end is the same as you are used to in Java.
Use auto-implemented properties when you don't have to do specific operations on the backing field. Use a ordinary property otherwise. Use get and set functions when the operation has side effects or is computationally expensive, use properties otherwise.
Regardless of which way you choose in C# the end result is the same. You will get a backinng variable with separate getter and setter methods. By using properties you are following best practices and so it's a matter of how verbose you want to get.
Personally I would choose auto-properties, the last version: public string Name { get; set; }, since they take up the least amount of space. And you can always expand these in the future if you need add something like validation.
Whenever possible I prefer public string Name { get; set; } as it's terse and easily readable. However, there may be times when this one is necessary
private string name;
public string Name {
get { return name; }
set { name = value; }
}
In C# the preferred way is through properties rather than getX() and setX() methods. Also, note that C# does not require that properties have both a get and a set - you can have get-only properties and set-only properties.
public boolean MyProperty
{
get { return something; }
}
public boolean MyProperty
{
set { this.something = value; }
}
First let me try to explain what you wrote:
// private member -- not a property
private string name;
/// public method -- not a property
public void setName(string name) {
this.name = name;
}
/// public method -- not a property
public string getName() {
return this.name;
}
// yes it is property structure before .Net 3.0
private string name;
public string Name {
get { return name; }
set { name = value; }
}
This structure is also used nowadays but it is most suitable if you want to do some extra functionality, for instance when a value is set you can it to parse to capitalize it and save it in private member for alter internal use.
With .net framework 3.0
// this style is introduced, which is more common, and suppose to be best
public string Name { get; set; }
//You can more customize it
public string Name
{
get;
private set; // means value could be set internally, and accessed through out
}
Wish you better luck in C#
As mentioned, all of these approaches result in the same outcome. The most important thing is that you pick a convention and stick with it. I prefer using the last two property examples.
like most of the answers here, use Automatic properties. Intuitive, less lines of code and it is more clean. If you should serialize your class, mark the class [Serializable]/ with [DataConract] attribute. And if you are using [DataContract] mark the member with
[DataMember(Name="aMoreFriendlyName")]
public string Name { get; set; }
Private or public setter depends on your preference.
Also note that automatic properties require both getters and setters(public or private).
/*this is invalid*/
public string Name
{
get;
/* setter omitted to prove the point*/
}
Alternatively, if you only want get/set, create a backing field yourself
Which one should I use, and what are the caveats or subtleties involved with each approach?
When going with properties there is one caveat that has not been mentioned yet: With properties you cannot have any parametrization of your getters or setters.
For example imagine you want to retrieve a list items and want to also apply a filter at the same time. With a get-method you could write something like:
obj.getItems(filter);
In contrast, with a property you are forced to first return all items
obj.items
and then apply the filter in the next step or you have to add dedicated properties that expose items filtered by different criteria, which soon bloats your API:
obj.itemsFilteredByX
obj.itemsFilteredByY
What sometimes can be a nuisance is when you started with a property, e.g. obj.items and then later discovered that getter- or setter-parametrization is needed or would make things easier for the class-API user. You would now need to either rewrite your API and modify all those places in your code that access this property or find an alternative solution. In contrast, with a get-method, e.g. obj.getItems(), you can simply extend your method's signature to accept an optional "configuration" object e.g. obj.getItems(options) without having to rewrite all those places that call your method.
That being said, (auto-implemented) properties in C# are still very useful shortcuts (for the various reasons mentioned here) since most of the time parametrization may not be needed – but this caveat stands.

Accessing members in your own class: use (auto)properties or not?

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.

using get vs property vs method [duplicate]

This question already has answers here:
Exposing Member Objects As Properties or Methods in .NET
(7 answers)
Closed 9 years ago.
if i have a private property in a class, i'm wondering what technically the difference is between the following three scenarios (memory usage, usability, best practice, etc):
class testClass
{
private string myString1 = "hello";
private string myString2 { get { return "hello"; } }
private string myString3() { return "hello"; }
}
apart from obviously being able to set the value in myString1 and not in myString2 or myString3, i'm wondering more about how these differ in terms of efficiency?
I try to follow these rules where possible:
Fields should be kept private
Properties should be used to expose data
Methods should be used to perform an action
There are obviously going to be some situations where every last drop of performance is important, but in general I would attempt to follow best-practice until profiling tells you that optimisation is needed.
There's a good article here: Why Properties Matter
I personally prefer properties for things without side effects and explicit getter if something is calculate on the fly. Eg:
class User {
private string username;
public string Username {
get { return username; }
set { username = value; }
}
public Post GetLatestPost() {
// query the database or whatever you do here.
}
}
And a lot of the APIs I've seen seem to do it similar. Hope that helps.
All these methods are very different in terms of what they get compiled to, though very much similar in terms of use. I'll try to summarise the differences in brief:
This is a simple private instance variable. It's easily going to be the most efficient when referencing.
This is a read-only property (i.e. a get but no set accessor).
This is a normal parameterless function. I suspect you're just offering these examples purely as a point of comparison, and realise that such a function is totally useless (as are private properties, in almost all cases). The layout (i.e. everything on one line) is also rather horrible.
Methods 2 and 3 are going to be equally inefficient compared to 1 in that they both involve the overhead of function calls. I don't know by memory the CIL code that they all compile to (maybe someone else can produce that), but they certainly involve a few more instructions, whereas referencing myString1 ought to only require a single instruction in CIL.
Not sure I can make a very useful comment on best practice without knowing more about the context, but method 2 (i.e. a private property) is generally seen as quite useless. The third method should never be used in my opinion (it's begging to be turned into a property). I think what you really want is just a plain old private variable, so definitely go for the first declaration. Public values should always be accessed as properties rather than variables in classes (i.e. a private/protected backing variable to a property), but that is slightly unrelated to your question. (You could find plenty of resources discussing the matter in a quick search anyway.) Finally, note that if your "property" is going to be read-only (i.e. not modified at any point), you really want to use a constant, i.e. private const string myString1 = "hello";.
Hope that helps clarify things a bit.
Thats a good question:
You have this alternatives:
private string myString = "hi!"; //Private Field
public string MyString //Property created to the private field
{
get {return myString;}
}
public string myString {get; private set;} //VS2008 automatic properties
public string getMyString() //Method Way
{
return myString;
}
As you can see the idea is the same, not to violate the encapsulation principle. Use the one you feel more comfortable with, all of them achieves the goal, but I recommend property way or the VIsual Studio 2008 automatic Property.
Is more concise and clear to see than the methods.
Hope this helps!
Regards!!
As far as best practices go,
class testClass
{
private string _myString;
public string myString { get { return _myString; } set { _myString = value; } }
public testClass()
{
myString = "Hello"; // Initial value.
}
}
Is generally recommended as it implements encapsulation (hiding internal state so that all manipulations pass through the methods/interface). Of course, the setters and getters are often methods themselves.
In C# 3.0, you can replace the above with:
class testClass
{
public string myString { get; set; }
public testClass()
{
...
}
}
As far as efficiency goes, you really should not be thinking about your design in terms of whether direct access to a variable is more efficient than a property. The difference is so small (if any) and the best practices guidelines so clear that you are just going astray worrying about efficiency.
All of the above discussions about design, style etc are valid. But the question is about performance. Easy enough to test. Wrapped some timers around each of the invokations, repeated to int32.Max.
On my machine the below code shows that the myString1 is much faster. (Note that I had to change the class definition to make the members public):
private void button2_Click(object sender, EventArgs e)
{
//performance test
testClass t = new testClass();
System.Diagnostics.Stopwatch sw1 = new System.Diagnostics.Stopwatch();
sw1.Start();
for (int i = 0; i < int.MaxValue; i++)
{
string result = t.myString1;
}
sw1.Stop();
System.Diagnostics.Stopwatch sw2 = new System.Diagnostics.Stopwatch();
sw2.Start();
for (int i = 0; i < int.MaxValue; i++)
{
string result = t.myString2;
}
sw2.Stop();
System.Diagnostics.Stopwatch sw3 = new System.Diagnostics.Stopwatch();
sw3.Start();
for (int i = 0; i < int.MaxValue; i++)
{
string result = t.myString3();
}
sw3.Stop();
MessageBox.Show(string.Format("Direct: {0}, Getter: {1}, Method: {2}"
, sw1.ElapsedMilliseconds.ToString()
, sw2.ElapsedMilliseconds.ToString()
, sw3.ElapsedMilliseconds.ToString()));
}
class testClass
{
public string myString1 = "hello";
public string myString2 { get { return "hello"; } }
public string myString3() { return "hello"; }
}

Categories

Resources