Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using get vs property vs method [duplicate]

Tags:

c#

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?

like image 896
benpage Avatar asked Sep 16 '25 01:09

benpage


2 Answers

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

like image 105
LukeH Avatar answered Sep 17 '25 16:09

LukeH


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.

like image 33
Armin Ronacher Avatar answered Sep 17 '25 14:09

Armin Ronacher