Solved

C# Properties In A Class

Posted on 2016-08-26
14
59 Views
Last Modified: 2016-09-02
Are properties needed in a class anymore?  I do use them in when I create a class that is just a model.
public MyModel
{
    public int ID { get; set: } = 0;
    public string FirstName { get; set: } = string.Empty;
    public string LastName { get; set: } = string.Empty;
}

Open in new window

But when creating a class in general.  I remember having a conversation with someone and I believe that properties were not needed otherwise.  They can just be passed in as parameters.
public class MyClass
{
   private string _myField = string.empty;

  public string MyMethod(string myValue)
 {
    _myField = myValue;
     //Do somthing....
 }
}

Open in new window

I don't remember the reason for it.
0
Comment
Question by:CipherIS
  • 5
  • 4
  • 2
  • +3
14 Comments
 
LVL 29

Accepted Solution

by:
Olaf Doschke earned 252 total points
Comment Utility
If a method has a parameter there's no need to store it as property for the method code to know this value, but properties surely still make very much sense.

There are several arguments for properties or fields in classes, both for just internal use or as public interface. The purists might only use private properties and getter setter methods, I don't want to go into detail about this discussion, but you may read about property procedures vs fields at https://msdn.microsoft.com/en-us/library/9d65as2e(v=vs.90).aspx

Anyway, a class is not merely a set of methods, it encapsulates all data you need and the code to act on it, to model it's behaviour. Iit has an interface to the public and can and should have an inner structure to keep a state and maintain it, otherwise you wouldn't have the need for a class, you merely would need the methods to act on your data and could always pass the data in.

Often enough you may have a couple of methods working together on something and then it is much more convenient to store that into a property and not need to pass it on and on, not only in recursion, you might have an entry method where the initial value comes in from extern and then set a private property to act on, the property value may become unimportant after a series of internal calls finally returns, it may stay valid and important in the whole life cycle and scope of the class instance. I don't know why you argue against properties, even considering encapsulation, a class without any interface and any publicly visible anything would be totally encapsulated, but also totally useless.

Bye, Olaf.
1
 
LVL 62

Assisted Solution

by:Fernando Soto
Fernando Soto earned 62 total points
Comment Utility
Hi CipherIS;

If you are going to adhere to the Object Oriented Programming paradigm, which in MHO is a good thing, then you should use them. Here is a snippet from Wikipedia, Property (programming)
A property, in some object-oriented programming languages, is a special sort of class member, intermediate between a field (or data member) and a method. Properties are read and written like fields, but property reads and writes are (usually) translated to get and set method calls. The field-like syntax is said to be easier to read and write than lots of method calls, yet the interposition of method calls allows for data validation, active updating (as of GUI visuals), or read-only 'fields'. That is, properties are intermediate between member code (methods) and member data (instance variables) of the class, and properties provide a higher level of encapsulation than public fields.
1
 
LVL 1

Author Comment

by:CipherIS
Comment Utility
I wish I could remember why it was recommended NOT to use them.  I do use them.  Just sparingly.
0
 
LVL 44

Assisted Solution

by:AndyAinscow
AndyAinscow earned 62 total points
Comment Utility
Crudely put.
Needed - no.
Useful - yes.

You can perform error checking easily with properties (get/set).  From management speak: trust is good, control is better.
1
 
LVL 12

Assisted Solution

by:funwithdotnet
funwithdotnet earned 62 total points
Comment Utility
What a good question!

I thought Olaf's and Fernando's comments were correct, precise & complimentary. Thank you, gentlemen.

I think it makes sense to use properties when it makes sense to use properties. :)

The original concern may have had to do with the extra overhead for a property vs. a field?

General Rule #1- Property access is 67% slower than field access.
General Rule #2- Rule #1 doesn't usually matter at all. Usually a negligible difference.
General Rule #3 - Use public properties instead of public fields. Like you, I forgot the specific reason, but I can think of one.
General Rule #4 - Use properties when objects represent real objects.
General Rule #5 - Use properties when input is processed.

I develop commercially, where everything is user-driven. I find it helps the entire SDLC and enterprise productivity to structure code based on user concepts.
1
 
LVL 29

Assisted Solution

by:Olaf Doschke
Olaf Doschke earned 252 total points
Comment Utility
>I wish I could remember why it was recommended NOT to use them.

Well, your code example gives one reasoning, instead of using a setter method, you can also pass in a value at some method not only setting the property, but also doing something with it. That's fine, but only looking at it from the perspective of a single method call instead of a set and a method call with one less parameter.

What if you want to do multiple things with one and the same value? Or with what the value which you initially set evolves to, so if you want to work with a state? Why should you then need to pass it in with every call? It's making a bad interface to not separate the setting of data and the processing of it, then you can also stop using OOP overall and just do structural programming with functions and procedures. So that reasoning you give is really bad, if it's not somewhat extended. You could do overloading and define methods with and without parameter and then make the first call with the parameter and secondary calls without it. I think it's simpler to have a preamble code setting properties and then always calling a method not needing that parameter.

Bye, Olaf.
1
 
LVL 1

Author Comment

by:CipherIS
Comment Utility
A lot of good information.
0
6 Surprising Benefits of Threat Intelligence

All sorts of threat intelligence is available on the web. Intelligence you can learn from, and use to anticipate and prepare for future attacks.

 
LVL 8

Assisted Solution

by:Prakash Samariya
Prakash Samariya earned 62 total points
Comment Utility
Are properties needed in a class anymore?
No, It is not required to have properties in class! Either you can create field/attribute/variable and give them value from parameter!

Ideally Class is collection of relevant information and its behaviors/actions!

You can create struct [Link] and use it where it is needed
1
 
LVL 1

Author Comment

by:CipherIS
Comment Utility
I think removing the properties also shortens the code.
0
 
LVL 44

Assisted Solution

by:AndyAinscow
AndyAinscow earned 62 total points
Comment Utility
As previously mentioned by numerous experts myself included earlier you do not need properties.  There are always multiple ways to do things - it doesn't mean they are all equally good though.
If you do not need to store the value in the class then use a parameter in the method call.  As soon as you have a requirement to store the value and save it between calls then using a parameter in a method to set it is not a good idea.

x.foo(param1)  <--store param for later use
x.bar()  <--use the stored value here

sometime later when you change the value in param1 BUT you don't need to use the method foo you can easily by accident just call x.bar().  Everything works, no error but the result is incorrect.  However x.foo(NewParam1) is something you don't want to do because that will mess something else up.  Things like this do happen and are a real pain to track down.
2
 
LVL 1

Author Comment

by:CipherIS
Comment Utility
Unless you create

x.foo(param1);
x.foo();

I used to create properties in my code in the past and set the fields that way.  Then I was told to rewrite the code to remove the properties and pass them as parameters and set the values that way.

I was just trying to remember what the reasoning was.  It does result in less lines of code.  

With properties, if you don't want to set one you don't have to but if it is a parameter you have to pass a value to it unless you are creating multiple methods as above but that can be cumbersome I think trying to code for it.
0
 
LVL 44

Expert Comment

by:AndyAinscow
Comment Utility
>>It does result in less lines of code.

So does removing error checking in the code and ...
0
 
LVL 1

Author Comment

by:CipherIS
Comment Utility
You need error checking.  But you can pass the properties in by parameter.
0
 
LVL 44

Expert Comment

by:AndyAinscow
Comment Utility
>>You need error checking.
Not always - but it makes sense to have it despite it resulting in more code.
0

Featured Post

Threat Intelligence Starter Resources

Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

Join & Write a Comment

In my previous two articles we discussed Binary Serialization (http://www.experts-exchange.com/A_4362.html) and XML Serialization (http://www.experts-exchange.com/A_4425.html). In this article we will try to know more about SOAP (Simple Object Acces…
It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
Excel styles will make formatting consistent and let you apply and change formatting faster. In this tutorial, you'll learn how to use Excel's built-in styles, how to modify styles, and how to create your own. You'll also learn how to use your custo…
When you create an app prototype with Adobe XD, you can insert system screens -- sharing or Control Center, for example -- with just a few clicks. This video shows you how. You can take the full course on Experts Exchange at http://bit.ly/XDcourse.

772 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now