Here is my code:
private int pressedMain = 1;
public int PressedMain
{
get
{
return pressedMain;
}
set
{
pressedMain = value;
}
}
And then I change the value of pressedMain:
pw.PressedMain++;
But in the following class my value is one, why and how can I slove this problem?
Example invoke, console prints 2 here
public class Foo
{
private int pressedMain = 1;
public int PressedMain
{
get
{
return pressedMain;
}
set
{
pressedMain = value;
}
}
}
class Program
{
static void Main(string[] args)
{
Foo foo = new Foo();
foo.PressedMain++;
Console.WriteLine(foo.PressedMain);
Debugger.Break();
}
}
Related
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();
}
}
I was trying to create simple event and below is the block of code but its not working. When I try to debug, as soon as we create Point object it is throwing "StackOverFlowException" at "Set" property(even before we assign the value p.x=10). What I am doing wrong?
using System;
namespace Workshop
{
public class Point
{
public int x
{
get { return x; }
set
{
x = value;
onPointeChanged();
}
}
public int y
{
get { return y; }
set
{
y = value;
onPointeChanged();
}
}
public event EventHandler pointchanged;
private void onPointeChanged()
{
if (pointchanged != null)
pointchanged(this, EventArgs.Empty);
}
}
public class Program
{
public static void Main(String[] args)
{
Point p = new Point();
p.pointchanged += HandleEvent;
p.x = 10;
}
public static void HandleEvent(object obj, EventArgs sender)
{
Console.WriteLine("Event Raised");
}
}
}
Thanks
You are calling the set method indefinitelly until you run out of stack memory. What you're doing with
x = value;
is you're calling the x property's setter, which in turn does x = value, so it calls itself, and so on, and so on for all eternity.
To fix this, introduce a field:
private int x;
public int X
{
get => x;
set
{
x = value;
OnPointChanged();
}
}
This is the proper way of creating properties with custom logic behind get and/or set. If you didn't have your OnPointChanged() logic you could just do
public int X { get; set; }
which would generate the following code for you under the hood:
private int x;
public int X { get => x; set => x = value; }
The problem is you are assigning the property a value in its own setter:
public int x
{
get { return x; }
set
{
x = value; // <-- see you are assigning `value` to your `x` property.
onPointeChanged();
}
}
This will loop over and over again ad infinitum. You need to create a backing field:
private int _myField;
public int BetterNameThanX
{
get { return _myField; }
set
{
_myField = value;
onPointeChanged();
}
}
You have defined properties and you return every own property which causes recursivity on get and set scopes. Try to define private attributes and expose it by properties:
public class Point
{
private int _x;
public int x
{
get { return _x; }
set
{
_x = value;
onPointeChanged();
}
}
private int _y;
public int y
{
get { return _y; }
set
{
_y = value;
onPointeChanged();
}
}
public event EventHandler pointchanged;
private void onPointeChanged()
{
if (pointchanged != null)
pointchanged(this, EventArgs.Empty);
}
}
Thanks to NHMountainGoat for an answer!
Implementing Interface looks a good choice so we have only the 'needed' method instanciated.
It looks like this now:
EDIT
class Machine
{
//REM: MachineConnexion is a link to the main server where asking the data
internal linkToPLC LinkToPLC;
public IlinkToPLC ILinkPLC;
public interface IlinkToPLC//Interface to linkPLC
{
Int16 MachineNumIS { get; set; }
}
internal class linkToPLC : IlinkToPLC
{
private Int16 Act_MachineNum;
private List<string> genlnkPLCCanvas;
private List<string> genlnkPLCworkingwith;
static private List<string> ListSymbolNoExist;
private string[] ListToPLClnk = {
"GlobalFolder.PMachine[{0}].",
"GlobalFolder.PMachine[{0}].STATE.",
"GlobalFolder.Machine[{0}].",
"GlobalFolder.Machine[{0}].STATE.",
};
public linkToPLC()//ctor
{
genlnkPLCCanvas = new List<string>(ListToPLClnk);
genlnkPLCworkingwith = new List<string>(ListToPLClnk);
ListSymbolNoExist = new List<string>();
Act_MachineNum = MachineNumIS;
}
public Int16 MachineNumIS { get { return (Int16)ReadWriteMachine("data"); } set { ReadWriteMachine("data", value); } }
public string ValueExist(string ValueToreach, bool WorkingDATA = false)
{
if (!WorkingDATA)
{
for (int inc = 0; inc < genlnkPLCworkingwith.Count; inc++)
{
string StrValueToReach = genlnkPLCworkingwith[inc] + ValueToreach;
if (MachineConnexion.SymbolExists(StrValueToReach))
{
ListSymbolNoExist.Clear();
return StrValueToReach;
}
else ListSymbolNoExist.Add(genlnkPLCworkingwith[inc] + ValueToreach);
}
}
else if (WorkingDATA)
{
string StrValueToReach = genlnkPLCworkingwith[10] + ValueToreach;
if (MachineConnexion.SymbolExists(StrValueToReach))
{
ListSymbolNoExist.Clear();
return StrValueToReach;
}
else ListSymbolNoExist.Add(genlnkPLCworkingwith[10] + ValueToreach);
}
if (ListSymbolNoExist.Count != 0)
{
string ErrorList = "";
for (int inc = 0; inc < ListSymbolNoExist.Count; inc++)
{
ErrorList = string.Concat(ErrorList + "Num: " + inc.ToString() + " " + ListSymbolNoExist[inc].ToString() + "\n");
}
Console.WriteLine("Error" + ErrorList);
}
return null;
}
public object ReadWriteMachine(string VariableName, object DataToWrite = null, bool WorkingDATA = false)
{
string valueToFind = "";
if (ValueExist(VariableName) != "FALSE")
{
if (DataToWrite != null) { MachineConnexion.WriteSymbol(valueToFind, DataToWrite); }
return MachineConnexion.ReadSymbol(valueToFind);
}
return VariableName;
}
}
public Machine() //constructor
{
LinkToPLC = new linkToPLC();
}
}
And It doesn't work telling me that the reference object is not defined to an instance of the object..... in the line : Machine() LinkToPLC = new linkToPLC();//REM I found the bug, it was me ;o)) 24112016
//REM 24112016
What are the main differences between those two concept: static Instance and Interface?
Example:
class Program
{
static void Main(string[] args)
{
ITestInterface InterInstance = new TestInterface();
//test Interface
bool value1 = true;
value1 = InterInstance.invert(value1);
InterInstance.print(value1);
//test Instance static
TestStaticInstance staticInstance = new TestStaticInstance();
staticInstance.Instance.invert(value1);
staticInstance.Instance.print(value1);
Console.ReadKey();
}
}
class TestInterface : ITestInterface
{
public bool invert(bool value)
{
return !value;
}
public void print(bool value)
{
Console.WriteLine(value.ToString()+"\n");
}
private void methodX()
{ }
}
interface ITestInterface
{
bool invert(bool value);
void print(bool value);
}
public class TestStaticInstance
{
public TestStaticInstance Instance;
public TestStaticInstance()
{
Instance = this;
}
internal bool invert(bool value)
{
return !value;
}
internal void print(bool value)
{
Console.WriteLine(value.ToString());
}
}
Thanks
Can you structure your other classes to take an instance of the link class? See:
/// <summary>
/// just a stub to demonstrate the model
/// </summary>
internal class Machine
{
public string ReadData() { return "this is data"; }
public void WriteData(string data) { Console.WriteLine(data); }
}
internal interface IMachineDataAccessor
{
string Read();
void Write(string data);
}
class LinkClass : IMachineDataAccessor
{
protected Machine _machine;
public LinkClass(Machine machine)
{
_machine = machine;
}
public void DoMyWork()
{
// insert work somewhere in here.
string dataFromMachine = Read();
Write("outbound data");
}
public string Read()
{
return _machine.ReadData();
}
public void Write(string data)
{
_machine.WriteData(data);
}
}
class PersistentClass
{
IMachineDataAccessor _machineImpl;
public PersistentClass(IMachineDataAccessor machineAccessImplementation)
{
_machineImpl = machineAccessImplementation;
}
public void DoMyWork()
{
string dataFromMachine = _machineImpl.Read();
// insert work here. Or anywhere, actually..
_machineImpl.Write("outbound data");
}
}
class StateClass
{
IMachineDataAccessor _machineImpl;
public StateClass(IMachineDataAccessor machineAccessImplementation)
{
_machineImpl = machineAccessImplementation;
}
public void DoMyWork()
{
string dataFromMachine = _machineImpl.Read();
// insert work here. Or anywhere, actually..
_machineImpl.Write("outbound data");
}
}
static void Main(string[] args)
{
LinkClass link = new LinkClass(new Machine());
PersistentClass persistent = new PersistentClass(link as IMachineDataAccessor);
StateClass state = new StateClass(link as IMachineDataAccessor);
persistent.DoMyWork();
state.DoMyWork();
link.DoMyWork();
}
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.
I'm having a small issue calling in the Icloneable interface
I've told the class I want to use the interface as such:
class UnitClass: ICloneable
and have placed in a function for Cloning
public Object Clone()
{
return this.MemberwiseClone();
}
however for some reason the program is telling me that I have not implemented System.ICloneable.clone() I even tried giving the function the explicit name like so...
public Object System.ICloneable.Clone()
but with little effect, anybody know what I'm doing wrong?
edit: Full class
class UnitClass: ICloneable
{
//-----------------------------------------------------------------------------------------------
//----------------------------------------------Variables----------------------------------------
private int unitID; //added for xml
private string unitName;
private int unitBaseHP;
private int unitCurrentHP;
private Carrier unitCarrier;
private int unitRechargeTime;
private int turnLastPlayed;
private int strengthAgainstFighters;
private int strengthAgainstBombers;
private int strengthAgainstTurrets;
private int strengthAgainstCarriers;
//-----------------------------------------------------------------------------------------------
//---------------------------------------------Constructor---------------------------------------
public UnitClass()
{
unitID = 0;
unitName = "Name Not Set";
unitBaseHP = 0;
unitCurrentHP = 0;
unitCarrier = null;//Carrier works as faction ie red/blue or left/right
unitRechargeTime = 0;
turnLastPlayed = 0;
strengthAgainstFighters = 0;
strengthAgainstBombers = 0;
strengthAgainstTurrets = 0;
strengthAgainstCarriers = 0;
}
//-----------------------------------------------------------------------------------------------
//---------------------------------------------Gets and Sets-------------------------------------
public int UnitID//public
{
set { unitID = value; }
get { return unitID; }
}
public string UnitName//public
{
set { unitName = value; }
get { return unitName; }
}
public int UnitBaseHP//public
{
set { unitBaseHP = value; }
get { return unitBaseHP; }
}
public int UnitCurrentHP//public
{
set { unitCurrentHP = value; }
get { return unitCurrentHP; }
}
public Carrier UnitCarrier//public
{
set { unitCarrier = value; }
get { return unitCarrier; }
}
public int UnitRechargeTime//public
{
set { unitRechargeTime = value; }
get { return unitRechargeTime; }
}
public int TurnLastPlayed//public
{
set { turnLastPlayed = value; }
get { return turnLastPlayed; }
}
public int StrengthAgainstFighters//public
{
set { strengthAgainstFighters = value; }
get { return strengthAgainstFighters; }
}
public int StrengthAgainstBombers//public
{
set { strengthAgainstBombers = value; }
get { return strengthAgainstBombers; }
}
public int StrengthAgainstTurrets//public
{
set { strengthAgainstTurrets = value; }
get { return strengthAgainstTurrets; }
}
public int StrengthAgainstCarriers//public
{
set { strengthAgainstCarriers = value; }
get { return strengthAgainstCarriers; }
}
//---------------------------------------------------------------------------
public object Clone()
{
return this.MemberwiseClone();
}
}
This built fine for me.
public class MyClone : ICloneable
{
public object Clone()
{
return this.MemberwiseClone();
}
}
You don't perhaps want to share any more of your class? Nothing is really jumping out at me.