Tufan Chand
Tufan Chand

Reputation: 752

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

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.

Upvotes: 3

Views: 3015

Answers (3)

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186813

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)}";
  }    
}

Upvotes: 4

MakePeaceGreatAgain
MakePeaceGreatAgain

Reputation: 37070

You need a static counter within MyClass that contains the number of instances that were already created:

class MyClass
{
    static int count = 0;
    public MyClass() { count++; }
}

Now you can easily access that counter within your Name-property:

string Name { get => $"Name{ counter }"; }

If there are multple threads that may concurrently increment the counter it´s better to use Interlocked.Increment(ref count) instead of count++ within the constructor.

Upvotes: 3

user9401448
user9401448

Reputation:

you'll need to store the value of TName in a private string;

private string m_TName;
public string TName
{
    get {return m_TName + counter;}
    set {
        if (m_TName != value){
            m_TName = value
        }
    }
}

if TName is always the same you can use

private string m_TName = "Default value";
public string TName
{
    get {return m_TName + counter;}
}

if you want to increment the counter each call

private string m_TName = "Default value";
public string TName
{
    get { 
        counter++;
        return m_TName + counter;
    }
}

if you want it on every instance as per HimBromBeere's comment

private string m_TName;
public string TName
{
    get {return m_TName;}
    set {
        if (m_TName != value){
            counter++;
            m_TName = value + counter;
        }
    }
}

if you want it on every instance as per HimBromBeere's comment AND you only want to set it once

private string m_TName;
public string TName
{
    get {return m_TName;}
    set {
        if (m_TName != value && m_TName == null){
            counter++;
            m_TName = value + counter;
        }
    }
}

Upvotes: 2

Related Questions