[Webinar] Streamline your web hosting managementRegister Today

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 78
  • Last Modified:

C# Properties In A Class

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
CipherIS
Asked:
CipherIS
  • 5
  • 4
  • 2
  • +3
7 Solutions
 
Olaf DoschkeSoftware DeveloperCommented:
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
 
Fernando SotoRetiredCommented:
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
 
CipherISAuthor Commented:
I wish I could remember why it was recommended NOT to use them.  I do use them.  Just sparingly.
0
Never miss a deadline with monday.com

The revolutionary project management tool is here!   Plan visually with a single glance and make sure your projects get done.

 
AndyAinscowFreelance programmer / ConsultantCommented:
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
 
funwithdotnetCommented:
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
 
Olaf DoschkeSoftware DeveloperCommented:
>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
 
CipherISAuthor Commented:
A lot of good information.
0
 
Prakash SamariyaIT ProfessionalCommented:
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
 
CipherISAuthor Commented:
I think removing the properties also shortens the code.
0
 
AndyAinscowFreelance programmer / ConsultantCommented:
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
 
CipherISAuthor Commented:
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
 
AndyAinscowFreelance programmer / ConsultantCommented:
>>It does result in less lines of code.

So does removing error checking in the code and ...
0
 
CipherISAuthor Commented:
You need error checking.  But you can pass the properties in by parameter.
0
 
AndyAinscowFreelance programmer / ConsultantCommented:
>>You need error checking.
Not always - but it makes sense to have it despite it resulting in more code.
0

Featured Post

Get expert help—faster!

Need expert help—fast? Use the Help Bell for personalized assistance getting answers to your important questions.

  • 5
  • 4
  • 2
  • +3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now