C
C
Collin2018-01-30 08:09:58
C++ / C#
Collin, 2018-01-30 08:09:58

How to use object from another method in C# console application?

Hello. Help, please, to understand. I don't understand how to use an instance of an object in another method:

public void Data()
{
   // Смотрю список портов, выбираю нужный и далее...
   SerialPort port1 = new SerialPort(portName);
   port1.BaudRate = 9600;
   poert1.StopBits = StopBits.One;

   port1.Open();

   port1.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);

   // Выполняю какие-то еще действия
}

private void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
{
   Console.WriteLine("Получил ответ");

   //тут мне нужно поработать с моим портом port1
   int buffSz = port1.BytesToRead; //И ожидаемо port1 не существует в текущем контексте
}

How to properly work with an instance of the SerialPort object and in general with any other instance of the object from another method?
In wpf, I somehow did not encounter such a problem. At first I thought about delegates, but, in my opinion, this is not quite what is needed in this case.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
P
Peter, 2018-01-30
@Collin

No way.
A method is an isolated space and there is no access to local variables of this space.
But in your case, the instance of the SerialPort object passes a reference to its instance to the delegate being connected, through the sender parameter, and in it you can do this:
var port = (SerialPort)sender;

A
Alexey Pavlov, 2018-01-30
@lexxpavlov

An object can only be accessed by reference to it. If there is a link, you can use it.
A reference to the port1 object is stored in the local variable of the Data method. After the call to this method ends, all local variables disappear. To refer to this object from another method, there are several ways:
1) store the reference in a class field, and not in a local variable. Access to fields is in all methods of the class (except static ones).
2) if the second method is called from the first one, then a reference can be passed as an argument to the second method. Your second method is not called from the Data method, in this case, it will not work like that.
3) the object itself can pass a reference to itself to other objects, then they will be able to use it (this is exactly what happens to you, as he saidPeter )
Please note that if you had not added an event handler, then after the call to the Data method was completed, there would not be a single reference to this object, and the garbage collector (GarbageCollector, GC) would mark it as garbage and delete it (before or later). And since you made an event handler, then this object is not garbage (it is used by another object). It becomes garbage when you remove the event handler.
What is the best way to send a link? Depending on the context (i.e., on the way this object is used):
1) if you created a temporary object that you used and is no longer needed, then pass a reference to it as arguments when calling methods that use it. When an object is no longer needed, the GC will quickly and painlessly delete it.
2) if you have created a permanent object that should work for some time after the end of the method in which the object was created, then you need to put a reference to it in a class field (or in a list, or somewhere else). As long as there is a link, the object remains. When it is no longer needed, then you need to remove the link to it (assign null or a new link in the field, remove it from the list, etc.). Don't forget to zero references to objects you don't need!
3) You can use indirect references (for example, event handlers), but this is usually inconvenient - it is not clear when object references will disappear, and in some cases, it will not be possible to remove the handler (again, this is difficult to do without a reference). Things like this are places for hard-to-find bugs. Therefore, it is better to use methods 1 or 2.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question