Increase the count in setter method for a property in c#

  • A+
Category:Languages

In a class I have declared one property like below

class MyClass {     public string TName     {          get {return "";}     }      // and some other properties .... } 

One method is returning the type IEnumerable<MyClass>, here I want to get the TName value as

Name 1, Name 2, Name 3, Name 4........ 

based on the count.

Problem:

How can I increment the value of counter in my setter method of the above property, so that i can append like "Name" + counter;

Or is there any other better way to achieve this without looping and fetching the count from DB.

Thank you in advance.

 


Same idea (we have a counter s_Count) but in case you want it thread safe we have to increment it in a special way:

class MyClass {   private static int s_Count;    public string TName {     get;   }    public MyClass() {     TName = $"Name {Interlocked.Increment(ref s_Count)}";   }     } 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: