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?
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
myString1ought 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.