Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between readonly property and function in .net?

Apart from an architectural point of view, i'm wondering if there is any difference in .net between a readonly property and a function. Are properties only conceptual wrappers around functions?

    Private m_Property As String 
    Public ReadOnly Property PropertyGet() As String
        Get
            Return m_Property
        End Get
    End Property

    Public Function FunctionGet() As String
        Return m_Property
    End Function

Disassembling IL shows that there's no difference apart from the name, but are there differences at another level? Is the getter just a function in short(!?)hand?


Edit: wow, i'm really sorry about not being able to mark multiple answers.

The first answer that pointed out the use of properties to serialize was the road to enlightenment since i had completely left this aspect out. Before that, the explanation of property vs function as "is" vs "does" felt arbitrary. Now, i grok it more.

I think the consensus on property being not time consuming stems from the "is"/serializable concept. If my property talks to a database to store the "is" value, it breaks in horrible ways.

like image 369
samy Avatar asked Oct 22 '10 12:10

samy


3 Answers

The difference is more semantic that functional; a property getter is in fact a function under the hood. The difference is more that as a programmer, you often expect that calling a property getter is a very cheap operation, while calling a function could potentially be more expensive.

Note that this is not necessarily the case; you can very well implement very light-weight functions, and very heavy property getters, but as a rule of thumb, a property getter should typically do nothing much more than simply get the value.

like image 193
Fredrik Mörk Avatar answered Sep 17 '22 23:09

Fredrik Mörk


There's one important difference if you use data binding, you simply cannot bind to a method, you can only bind to properties.

like image 20
vc 74 Avatar answered Sep 16 '22 23:09

vc 74


The whole property thing was - probably - conceived to avoid getting a bunch of separate GetSomething(), SetSomething(var x) methods, which used to be the norm in, for example, Java in the early 2000s for data access. This to avoid publicly exposed variables.

Believe me, those classes looked awful. I personally think the property concept is a great leap forward in readability and structure.

like image 31
Marcus L Avatar answered Sep 17 '22 23:09

Marcus L