I am new to c# so I don't understand well why I am getting this error. I am using IngenicoPOS class to create a sale, but I want to create the sale action inside a pos operation class so it is separated from the rest. However, when I try to connect the posDevice I got that an error where it said postDevice.Connect doesn't exist in the current context. For the connection part, I follow their document. Now, I think I am doing wrong when I create a new post device or because I am trying to create a connection inside a class. The full code:
class PosOperations
{
public PosOperations(string operationType, string paymentType, int amountToPay)
{
this.OperationType = operationType;
this.PaymentType = paymentType;
this.AmountToPay = amountToPay;
}
public string OperationType { get; }
public int AmountToPay { get; }
public string PaymentType { get; }
private const string PORT = "COM9";
private POS posDevice = new POS(PORT);
posDevice.Connect(); // Will return true if connection is made, otherwise will return false
}
Can you help me? How can I use another class's methods inside another class? Why is this not found in the current context??
CodePudding user response:
Types (of which class is one) can only contain members. You've got a field member called posDevice. You're allowed to instantiate that field on the same line as its declaration, but you're not allowed to run any other statements using that field.
This is what the Constructor is used for. Move the initialization of the field to the constructor as well as the additional Connect call you want to make.
public PosOperations(string operationType, string paymentType, int amountToPay)
{
this.OperationType = operationType;
this.PaymentType = paymentType;
this.AmountToPay = amountToPay;
posDevice = new POS(PORT);
posDevice.Connect();
}
// ...
private POS posDevice;
Now, some optional suggestions for you to research and implement later:
- Make
posDevicereadonly, as right now only the Constructor should be assigning the varaible - Take into account the return value of
Connect(). Do something when it returns false, like maybe throw an exception. - Implement
IDisposableto close the connection when thePosOperationsinstance is disposed.
