Reputation: 2333
In the C# code below, I am trying to execute the code in the consoleread
method by instantiating it within the Main
method. I am a complete beginner at OOP and it seems to work but I just want to be sure if this is the right way to do it?
using System;
using System.Collections.Generic;
using System.Text;
using System.IO.Ports;
namespace ConsoleApplication1
{
class ConsoleRead
{
public void consoleread()
{
string[] sPorts = SerialPort.GetPortNames();
foreach (string port in sPorts)
{
var serialPort = new SerialPort();
serialPort.PortName = port;
serialPort.Open();
serialPort.WriteLine("ATI");
var message = Console.ReadLine();
}
}
}
class Program
{
static void Main(string[] args)
{
ConsoleRead c = new ConsoleRead();
c.consoleread();
}
}
}
Upvotes: 0
Views: 128
Reputation: 48985
Yes it's alright. You have a class with an instance method, so you instantiate that class and call the method against the instance.
Now, for the question "is this the right way to do", then it's a little hard to answer without more background. In your particular example, if the only goal of your application is to write some string on serial ports without any reusability concerns, then creating a class that is instantiated only once is probably useless, you should just move the code from your consoleread
method to the main
method.
Upvotes: 1
Reputation: 48568
Yes its the right way. But are you facing any problems in it?
Upvotes: 1