Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

C# Properties In A Class

Posted on 2016-08-26
14
Medium Priority
?
75 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 30

Accepted Solution

by:
Olaf Doschke earned 1008 total points
ID: 41772305
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 64

Assisted Solution

by:Fernando Soto
Fernando Soto earned 248 total points
ID: 41772314
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
ID: 41772388
I wish I could remember why it was recommended NOT to use them.  I do use them.  Just sparingly.
0
Get free NFR key for Veeam Availability Suite 9.5

Veeam is happy to provide a free NFR license (1 year, 2 sockets) to all certified IT Pros. The license allows for the non-production use of Veeam Availability Suite v9.5 in your home lab, without any feature limitations. It works for both VMware and Hyper-V environments

 
LVL 45

Assisted Solution

by:AndyAinscow
AndyAinscow earned 248 total points
ID: 41772439
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 248 total points
ID: 41772665
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 30

Assisted Solution

by:Olaf Doschke
Olaf Doschke earned 1008 total points
ID: 41772690
>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
ID: 41774024
A lot of good information.
0
 
LVL 10

Assisted Solution

by:Prakash Samariya
Prakash Samariya earned 248 total points
ID: 41774748
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
ID: 41774768
I think removing the properties also shortens the code.
0
 
LVL 45

Assisted Solution

by:AndyAinscow
AndyAinscow earned 248 total points
ID: 41774813
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
ID: 41775469
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 45

Expert Comment

by:AndyAinscow
ID: 41775770
>>It does result in less lines of code.

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

Author Comment

by:CipherIS
ID: 41776471
You need error checking.  But you can pass the properties in by parameter.
0
 
LVL 45

Expert Comment

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

Featured Post

Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article shows how to deploy dynamic backgrounds to computers depending on the aspect ratio of display
This article aims to explain the working of CircularLogArchiver. This tool was designed to solve the buildup of log file in cases where systems do not support circular logging or where circular logging is not enabled
Video by: ITPro.TV
In this episode Don builds upon the troubleshooting techniques by demonstrating how to properly monitor a vSphere deployment to detect problems before they occur. He begins the show using tools found within the vSphere suite as ends the show demonst…
Screencast - Getting to Know the Pipeline

927 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