Property methods vs fields in C#


Dashnick

Using C# - if I have a property of an object that, for example, returns the number of elements in that object's fields array, like NumColsthis:

public string[][] Table { get; }  // Jagged 2D Table
public int NumRows { get { return Table.Length; } }  // number of rows in the table
public int[] NumCols {
    // number of columns in each row
    get
    {
        var NumCols = new int[NumRows];
        for (int i=0; i<NumRows; i++) { NumCols[i] = Table[i].Length; }
        return NumCols;
    }
}  

Would it be a performance issue to have to recalculate this statistic every time if I were to reference this property NumColsa lot ? If the runtime Tabledoesn't change , is the runtime smart enough so it doesn't have to be recomputed every time ? Should I manually set it as a field and then update it as needed?

stamp

Whenever a property value is accessed, the property getter will be executed. In this way, they are the same as methods that Get<PropertyName>just return a value .

If you want to avoid this, you should consider caching the value, e.g. using a lazy approach like this:

private int[] numCols = null;
public int[] NumCols
{
    get
    {
        if (numCols == null)
        {
            numCols = ExpensiveCalculation();
        }
        return numCols;
    }
}

In general, you should avoid putting expensive stuff in property getters, because the expectation for a property is that you can access the value very quickly with little overhead. If you find yourself needing a more complex process to get a value, and not suitable for caching as described above, then you should consider writing a real get method. This way the user of the method will implicitly know that there is an overhead compared to a simple property:

public int[] GetNumCols()
{
     return ExpensiveCalculation();
}

Related


Fields vs methods in C++ class std::numeric_limits

Greg 82 Why in a template class std::numeric_limitsin C++ , digits(and other classes) are defined as (static const) fields of the class, but are min()again max()methods, since those methods just return garbled values? Thanks in advance. username Initialization

Defining Private Fields and Property vs. Property

Jose Lopez Garcia Following OOP best practices, it is best to use the following code: class Car { private Driv driver; public Driv Driver { get { return driver; } set { driver = value; } } } Or this? class Car { public Dri

Hibernate/JPA - Annotating bean methods vs fields

benstpierre: I have a simple question about Hibernate usage. I keep seeing people using JPA annotations in one of two ways, by annotating the fields of the class and also by annotating the get method of the corresponding bean. My question is the following: wit

Hibernate/JPA - Annotating bean methods vs fields

benstpierre: I have a simple question about Hibernate usage. I keep seeing people using JPA annotations in one of two ways, by annotating the fields of the class and also by annotating the get method of the corresponding bean. My question is the following: wit

Hibernate/JPA - Annotating bean methods vs fields

Benstpierre : I have a simple question about Hibernate usage. I keep seeing people using JPA annotations in one of two ways, by annotating the fields of the class and also by annotating the get method of the corresponding bean. My question is the following: wi

C#: Anonymous methods vs named methods

c sharp user I'm new to SO and programming and learning with bits and pieces of technical (C#) jargon every day. After googling for a while, here is what I researchedmethods A method is a block of statements for code reusability and it also supports overloadin

C#: Anonymous methods vs named methods

c sharp user I'm new to SO and programming and learning with bits and pieces of technical (C#) jargon every day. After googling for a while, here is what I researchedmethods A method is a block of statements for code reusability and it also supports overloadin

C#: Anonymous methods vs named methods

c sharp user I'm new to SO and programming and learning with bits and pieces of technical (C#) jargon every day. After googling for a while, here is what I researchedmethods A method is a block of statements for code reusability and it also supports overloadin

C#: Anonymous methods vs named methods

c sharp user I'm new to SO and programming and learning with bits and pieces of technical (C#) jargon every day. After googling for a while, here is what I researchedmethods A method is a block of statements for code reusability and it also supports overloadin

How to count initialization fields in C# methods?

Delier My class looks like this: public class Person { public string Name { get; set; } public string Surname { get; set; } public string Nickname{ get; set; } public Person GetPersonData() { return new Person() {

Inherit C++ with static methods/fields

Tommy Lee Jones I have a class that EnemyI want to be the base class for all enemy types and also want to be a pure abstract class. At this point, all its members and methods should be shared by the derived class. In particular, there are methods that loadText

Static Blocks vs Static Methods - Initializing Static Fields

null Out of curiosity, I measured performance between static blocks and static method initializers. First, I implemented the above method in two separate java classes like this: First: class Dummy { static java.util.List<Integer> lista = new java.util.Arra

Static Blocks vs Static Methods - Initializing Static Fields

null Out of curiosity, I measured performance between static blocks and static method initializers. First, I implemented the above method in two separate java classes like this: First: class Dummy { static java.util.List<Integer> lista = new java.util.Arra

Static Blocks vs Static Methods - Initializing Static Fields

null Out of curiosity, I measured performance between static blocks and static method initializers. First, I implemented the above method in two separate java classes like this: First: class Dummy { static java.util.List<Integer> lista = new java.util.Arra

Objective C class methods vs C functions

Mike D While working on an open source project, I came across the declaration and implementation of the following C function: // FSNData.h NSString *stringForMimeType(MimeType type); @interface FSNData : NSObject // All the expected objective-c property and i

CSS property checking in jQuery vs. regular different methods

Marwan Bshara I would like to know what is the difference between these two codes $('.stars li').each(function(i){ if(this.style.display !== 'none'){ this.style.display = 'none'; return false; } }); and this code $('.stars li').each(function(i){

CSS property checking in jQuery vs. regular different methods

Marwan Bshara I would like to know what is the difference between these two codes $('.stars li').each(function(i){ if(this.style.display !== 'none'){ this.style.display = 'none'; return false; } }); and this code $('.stars li').each(function(i){

CSS property checking in jQuery vs. regular different methods

Marwan Bshara I would like to know what is the difference between these two codes $('.stars li').each(function(i){ if(this.style.display !== 'none'){ this.style.display = 'none'; return false; } }); and this code $('.stars li').each(function(i){

c# generics for property helper methods

Space Marine 104 I can't find a good way to make this DRY in .Net Core. (don't repeat yourself). How to do this so as not to repeat most of the logic? Here are two ways: public static string GetCategory(this Enum val) { CategoryAttribute[] attr

c# generics for property helper methods

Space Marine 104 I can't find a good way to make this DRY in .Net Core. (don't repeat yourself). How to do this so as not to repeat most of the logic? Here are two ways: public static string GetCategory(this Enum val) { CategoryAttribute[] attr

c# generics for property helper methods

Space Marine 104 I can't find a good way to make this DRY in .Net Core. (don't repeat yourself). How to do this so as not to repeat most of the logic? Here are two ways: public static string GetCategory(this Enum val) { CategoryAttribute[] attr

Virtual breakers vs regular methods in C++

Matthew Consider the following three C++ programs: program 1 struct base{ virtual ~base() =0; }; struct derived: public base{ ~derived(); }; derived::~derived(){} int main(){} program 2 struct base{ virtual ~base() =0; }; struct derived: public base

Virtual breakers vs regular methods in C++

Matthew Consider the following three C++ programs: program 1 struct base{ virtual ~base() =0; }; struct derived: public base{ ~derived(); }; derived::~derived(){} int main(){} program 2 struct base{ virtual ~base() =0; }; struct derived: public base

Private Methods vs Lambdas in C++

username My question refers to: Using Lambda Expressions with Private Methods Now that lambda functions are part of C++, you can use them to tidy up a class's interface. In C++, how does lambda usage compare to private methods? Are there better alternatives to

Virtual breakers vs regular methods in C++

Matthew Consider the following three C++ programs: program 1 struct base{ virtual ~base() =0; }; struct derived: public base{ ~derived(); }; derived::~derived(){} int main(){} program 2 struct base{ virtual ~base() =0; }; struct derived: public base