Click here to Skip to main content
15,888,816 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
why my set block is executing multiple times when i assign value to my property
my code is--------
C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace practice
{
    class Program
    {
        public static int eno
        {
            get {
                return 1;
            }
            set {
                eno = value;
            }
        }
        static void Main(string[] args)
        {

            Console.WriteLine(eno);
            eno = 5;
            Console.WriteLine(eno);
            Console.ReadLine();
     
        }
    }
}
Posted

1 solution

Well...yes - it will...
C#
public static int eno
{
    get {
        return 1;
    }
    set {
        eno = value;
    }
}
So
C#
eno = 5;
Calls the setter, which does:
C#
int value = 5;
eno = 5;
Which calls the setter, which does:
C#
int value = 5;
eno = 5;
Which calls the setter, which does:
C#
int value = 5;
eno = 5;
...

You can't set the value of a property from within the property!
Try this:
C#
private static int _Eno
public static int Eno
{
    get {
        return 1;
    }
    set {
        _Eno = value;
    }
}
Though why you return a constant value from the getter is anyones guess!
 
Share this answer
 
Comments
rakeshjena 26-May-14 4:02am    
thanks @originalgriff.i am new to c# so just experimenting.marked as answer.

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