How to retain old value when setting variable on c# class - c#

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!

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

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

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

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

string _entry;
public string Entry
{
get { return _entry; }
set { _entry += value; }
}

Related

Serializing a class as one of its properties

When I serialize an object using JsonConvert using the following code:
JsonConvert.SerializeObject(new Foo())
The result is:
{"count":{"Value":3},"name":{"Value":"Tom"}}
I would like the result to look like this. So without the embedded { "Value": * } structure.
{"count":3,"name":Tom}
I need use JObject.FromObject and JsonConvert.SerializeObject.
The code for the Foo class:
public class Foo
{
public DeltaProperty<int> count = new DeltaProperty<int>(3);
public DeltaProperty<string> name = new DeltaProperty<string>("Tom");
}
public class DeltaProperty<T>
{
public T Value
{
get
{
m_isDirty = false;
return m_value;
}
set
{
if (!m_value.Equals(value))
{
m_isDirty = true;
m_value = value;
}
}
}
private bool m_isDirty = default;
private T m_value = default;
public DeltaProperty(T val)
{
Value = val;
}
public bool ShouldSerializeValue()
{
return m_isDirty;
}
public override string ToString()
{
return m_value.ToString();
}
}

C# add items to list from class then add list items to listbox

I'm a student in a C# class and this is my introductory assignment to Classes, so please bear with me. When the New button is pressed, a CPerson object will be created using the name and phone values and the object will be added to a List<>.
class CPerson
{
private string m_sName;
private string m_sPhone;
public string Name
{
get { return this.m_sName; }
set
{
this.m_sName = value;
}
}
public string Phone
{
get { return this.m_sPhone; }
set
{
this.m_sPhone = value;
}
}
}
public partial class Form1 : Form
{
private List<CPerson> PhoneNum = new List<CPerson>(); //<CPerson> or <string>?
public Form1()
{
InitializeComponent();
newbutton.Enabled = false;
changebutton.Enabled = false;
savebutton.Enabled = false;
}
private void newbutton_Click(object sender, EventArgs e)
{
changebutton.Enabled = true;
savebutton.Enabled = true;
PhoneNum.Add(new CPerson { Name = Namebox.Text + " : ", Phone = phonebox.Text });
listBox1.Items.Add(PhoneNum); //text = "Collection"
}
The assignment says "The CPerson ToString() override will be used to display the name and phone number in the listbox" as shown in the above image, which I don't necessarily understand, but I'm guessing I have to use something like this?
CPerson data = new CPerson();
data.ToString();
Either way, as the code is now, all I get in my listbox is "(Collection)". Any help would be appreciated!
That is asking to override the ToString() method. You can do it like this:
class CPerson
{
private string m_sName;
private string m_sPhone;
public string Name
{
get { return this.m_sName; }
set
{
this.m_sName = value;
}
}
public string Phone
{
get { return this.m_sPhone; }
set
{
this.m_sPhone = value;
}
}
public override string ToString()
{
return Name + ": " + Phone;
}
I did not get right the part of adding to the list, but I assume you can do the following using ToString():
listBox1.Items.Add(data.ToString());
Close...
class CPerson
{
private string m_sName;
private string m_sPhone;
public string Name
{
get { return this.m_sName; }
set
{
this.m_sName = value;
}
}
public string Phone
{
get { return this.m_sPhone; }
set
{
this.m_sPhone = value;
}
}
public override string ToString()
{
return Name + ": " + Phone;
}
}
}

Creating two C# class definitions with a driver to test classes, but not sure why so many errors?

I am new to C# and was asked to create two class definitions (customer and order) using partial code and with the suggested class names, methods, contructors and following an example. I am not sure why I am getting so many errors when I build/debug?
After this is finished, I need to create another program that builds onto this one. Our instructor also asked us not to use validation...
Some of my most common errors are:
expected: ; (in a place in my code where I believe there should not be a semi-colon and
Error "Expected class, delegate, enum, interface, or struct.
Here is my code:
public class clsOrder
{
//declare class variables
protected string cstrDescription;
protected int cintQuantity;
protected decimal cdecPrice;
protected decimal cdecExtendedPrice;
//shared variables
static decimal cdecTotalPrice;
static int cintTotalCount;
//declare constructors
public clsOrder();
}
public clsOrde r(string strDescription,
int intQuantity, decimal decPrice)
}
//declare property methods
{
this.Description = string strDescription;
this.Quantity = int intQuantity;
this.Price = decimal decPrice;
//declare read-only properties
public decimal ExtendedPrice
}
public string Description
{
get
{
return strDescription;
}
set
{
strDescription = value;
}
}
public int Quantity
{
get
{
return intQuantity;
}
set
{
intQuantity = value;
}
}
public decimal Price
{
get
{
return decPrice;
}
set
{
decPrice = value;
}
}
get
{
return cdecExtendedPrice;
}
}
//declare Shared (static) ReadOnly Properites
public static decimal TotalPrice
{
get
{
return cdecTotalPrice;
}
}
public static int TotalCount
{
get
{
return cintTotalCount;
}
}
//declare supporting methods
public void calcExtendedPrice()
{
cdecExtendedPrice = cintQuantity * cdecPrice;
}
public void accumulateTotals()
{
cdecTotalPrice += cdecExtendedPrice;
cintTotalCount += 1;
}
public static void resetTotals()
{
cdecTotalPrice = 0;
cintTotalCount = 0;
}
}//end of Class
}//end of namespace
And
public class clsCustomer
{
//declare class variables
private string cstrName;
private string cstrStreet;
private string cstrCity;
private string cstrState;
private string cstrZip;
//declare constructors
public class clsCustomer()
}
public clsCustomer(string strName,
string strStreet, string strCity,
string strState, string strZip)
}
//declare property methods
{
this.Name = cstrName;
this.Street = cstrStreet;
this.City = cstrCity;
this.State = cstrState;
this.Zip = cstrZip;
}
public string Name
{
get
{
return cstrName;
}
set
{
cstrName = value;
}
}
public string Street
{
get
{
return cstrStreet;
}
set
{
cstrStreet = value;
}
}
public string City
{
get
{
return cstrCity;
}
set
{
cstrCity = value;
}
}
public string State
{
get
{
return cstrState;
}
set
{
cstrState = value;
}
}
public string Zip
{
get
{
return cstrZip;
}
set
{
cstringZip = value;
}
}
Any help would be very much appreciated, thank you.

c# how to give constructor fields from another class

I have 3 Classes : Masina (Car), Destinatie (Destination) and MasinaDestinatie (CarDestination).
I need the third class to get the values of the car number _nr_masina and the destination _cod_dest through it's own constructor.
I need to make a constructor with parameters in the third class that stores the values of _nr_masina and _cod_dest.
Anyone know how can i do this exactly? I've tried making the private fields public and putting them as parameters but that doesn't work...
The classes:
namespace Problema_test
{
class Masina
{
private string _nr_masina = string.Empty;
private string _valoare = string.Empty;
private string _an_fabricatie = string.Empty;
public Masina(string nr_masina,string valoare, string an_fabricatie)
{
_nr_masina = nr_masina;
_valoare = valoare;
_an_fabricatie = an_fabricatie;
}
public string Numar
{
get { return _nr_masina; }
set { _nr_masina = value; }
}
public string Valoare
{
get { return _valoare; }
set { _valoare = value; }
}
public string Anul
{
get { return _an_fabricatie; }
set { _an_fabricatie = value; }
}
}
class Destinatie
{
private string _cod_destinatie = string.Empty;
private string _adresa = string.Empty;
public Destinatie(string cod_destinatie, string adresa)
{
_cod_destinatie = cod_destinatie;
_adresa = adresa;
}
public string CodDest
{
get { return _cod_destinatie; }
set { _cod_destinatie = value; }
}
public string Adresa
{
get { return _adresa; }
set { _adresa = value; }
}
}
class MasinaDestinatie
{
// how can i make this work?
public MasinaDestinatie(string numarMasina, string codDest)
{
}
}
}
You can store the values inside properties
class MasinaDestinatie
{
public string Numar {get;set;}
public string CodDest {get;set;}
public MasinaDestinatie(string numarMasina, string codDest)
{
Numar = numarMasina;
CodDest = codDest;
}
}
To use the class you have do something like this
var masina = new Masina("Dacia","2000","1992");
var destinatie = new Destinatie("123", "Romania");
var masinaDestinatie = new MasinaDestinatie(masina.Numar, destinatie.CodDest);
Solution 2: As #blas-soriano sugested you can store the reference of the objects (Masina, Destinatie), this way you won't have problems (i.e. CodDest exist only in MasinaDestinatie but not in Destinatie, and many others).
class MasinaDestinatie
{
private Masina _masina {get;set;}
private Destinatie _destinatie {get;set;}
public string Numar { get { return _masina.Numar; } }
public string CodDest { get { return _destinatie.CodDest; } }
public MasinaDestinatie(Masina masina, Destinatie destinatie)
{
_masina = masina;
_destinatie = destinatie;
}
}
To use the class you have do something like this
var masina = new Masina("Dacia","2000","1992");
var destinatie = new Destinatie("123", "Romania");
var masinaDestinatie = new MasinaDestinatie(masina, destinatie);

How can I use a certain class as String?

Code1
public class Human
{
private string h_name = "";
private string h_gender = "Male";
private int h_age = 0;
public string Name
{
get { return h_name; }
set { h_name = value; }
}
public string Gender
{
get { return h_name; }
set { h_name = value; }
}
public int Age
{
get { return h_age; }
set { h_age = value; }
}
}
Code2
public class Here
{
public static void Main(String[] args)
{
Human hm = new Human();
hm.Name = "Bill";
hm.Gender = "Male";
hm.Age = 20;
}
}
Now, I'd like to use the variable "hm" as String where hm will return the Name property... something like:
string person = hm;
Console.WriteLine(person + " has greeted you!");
What will I do? Should I make an Extension or something?
I overridden the ToString() method, and yes, it works on Console.WriteLine()
but now, I want to store it as string in a string variable
string person = hm;
Console.WriteLine(person);
and I get this
Cannot implicitly convert type 'Human' to 'string'
I also want to use it in my VB.NET program, but it gives me this error when I concatenate it:
Operator '&' is not defined for types 'String' and 'Human'
You can declare an implicit conversion from your type to string using operator overloading. But it's a bad idea. I suggest you to override ToString method in your class instead, then you can just output it like this:
Console.WriteLine(hm + " has greeted you!");
There is also a good documentation on how to override ToString method
How To: Override the ToString Method (C# Programming Guide)
An implicit convention by adding the following to the Human class would work
public static implicit operator string(Human h)
{
return h.Name;
}
Although i think the best way is to override the ToString Method like so
public override string ToString()
{
return Name;
}
You could override the ToString method:
public class Human
{
private string h_name = "";
private string h_gender = "Male";
private int h_age = 0;
public string Name
{
get { return h_name; }
set { h_name = value; }
}
public string Gender
{
get { return h_name; }
set { h_name = value; }
}
public int Age
{
get { return h_age; }
set { h_age = value; }
}
public override string ToString()
{
return Name;
}
}
Override ToString() method.
public class Human
{
public override ToString() { return Name }
private string h_name = "";
private string h_gender = "Male";
private int h_age = 0;
public string Name
{
get { return h_name; }
set { h_name = value; }
}
public string Gender
{
get { return h_name; }
set { h_name = value; }
}
public int Age
{
get { return h_age; }
set { h_age = value; }
}
}
Your code would then look like this:
Console.WriteLine(hm + " has greeted you!");
vb.net answer:
As state by others, you need to define a conversion operator. If you want to support string concatenation then you also need to define the & operator.
Public Class Human
Public Property Name As String
Public Shared Widening Operator CType(value As Human) As String
Return value.Name
End Operator
Public Shared Operator &(left As Human, right As String) As String
Return (left.Name & right)
End Operator
Public Shared Operator &(left As String, right As Human) As String
Return (left & right.Name)
End Operator
Public Overrides Function ToString() As String
Return Me.Name
End Function
End Class

Categories

Resources