-4

I want to create a class that can set multiple value and not delete the old one that was set already, instead add it and the old value. Here is my sample.

myClass myCls = new myClass();

myCls.setString = "My first string!";
myCls.setString = "My second string!";
myCls.setString = "My third string!";
string printMe = myCls.getString();

Console.WriteLine(printMe);

And when it will output something like;

//My first string!My second string!My third string!
tiltdown
  • 441
  • 1
  • 11
  • 26

5 Answers5

1

You can try with this class:

public class ValueKeeper {

    private List<object> values;

    public object Value {
        get { return ToString(); }
        set { values.Add(value); }
    }

    public ValueKeeper() {
        values = new ArrayList<object>();
    }

    public override string ToString() {
        string result = String.Empty;
        foreach(object value in values) result += value.ToString();
        return result;
    }
}

It can be improved of course, but it would satisfy your needs.


Example

ValueKeeper valueKeeper = new ValueKeeper();

valueKeeper.Value = 1;
valueKeeper.Value = "This is a string";
valueKeeper.Value = someCustomObject;

string str = valueKeeper.Value;
Console.WriteLine(str); //PRINTS OUT "1This is a stringxxxxx"
                        //Where "xxxx" is the string representation of the custom object
Matias Cicero
  • 23,674
  • 11
  • 73
  • 143
1

One way to do it would be to have a new property on your myClass

public class myClass
{
    private string _setString;
    public string setString 
    {
            get
            {
                 return _setString;
             }
            set
            {
                 AuditTrail +=  value;
                 _setString = value;
            }
    }

    public string AuditTrail{get;set;}

}

Then in your main method you'd put:

Console.WriteLine(AuditTrail);
asven
  • 133
  • 1
  • 7
0
string _entry;
public string Entry
{
    get { return _entry; }
    set { _entry += value; }
}
Dom
  • 716
  • 4
  • 11
0

You can create class like this.

class MyClass
{
   private string myString;
   public string MyString
   {
    get
     {
       return myString;
     }
    set
     {
       myString += value;
     }
    }
 }

In you Program you can use like this

MyClass c = new MyClass();
c.MyString = "String 1";
c.MyString = "String 2";
Console.WriteLine(c.MyString);
Kiran Hegde
  • 3,651
  • 1
  • 14
  • 14
0

This seems like an odd request but it can be done!

 class myClass
    {
        //Properties
        private string privateString;

        //Constructor
        public myClass()
        {

        }

        //Methods
        public void setString(string val)
        {
            privateString += val;
        }

        public string getString()
        {
            return privateString;
        }

    }
Nick H.
  • 1,608
  • 14
  • 19