Click here to Skip to main content
15,888,226 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
please help ...
please show me the use of property in calling a function

What I have tried:

i have done nothing. i am in great trouble please help me
Posted
Updated 5-Feb-21 20:23pm

1 solution

It's generally considered a bad idea to do that: it can lead to "side effect properties" where the user (who doesn't look at what the code of the property does) isn't expecting the property getter to change the state of anything - in the same way that you don't expect using the value of a variable to do anything other than return the value:
C#
int x = 666;
int y = x + 1;
You (and I, and everybody else) expects that code to just fetch the value of x - 666 - and add one to it before storing 667 in y.
If the integer getter fetched the value and also updated a different variable with the sum of values fetched, it would be unexpected and very confusing!

So generally speaking, a getter should do as little as is needed to return the value - calling a method from within a getter leave a lot of scope for later mods to introduce side effects which may create some very complicated to find and fix problems and should be avoided for that reason.

But ... it's possible, even easy to do:
C#
private int[] data = { 1, 2, 3, 4, 5, 10, 11, 12};
public int Sum{ get {return calculateSum(data);} }
private int calculateSum(IEnumerable<int> collection)
    {
    int result = 0;
    foreach (int t in collection)
        {
        result += t;
        }
    return result;
    }
}
 
Share this answer
 
Comments
Member 12712527 6-Feb-21 3:12am    
okay thank you sir

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900