In Visual C# 2010 Express, when pressing ctr+F7 with the code below, why is the console not opening? I have several .cs documents in the same project but I only want to execute this one.
using System;
using System.Collections.Generic;
using System.Text;
using System.IO.Ports;
namespace ConsoleRead
{
protected class consoleread
{
public void GetPortName ()
{
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();
}
}
}
}
Many thanks in advance!
This is because Ctlr + F7 will execute your application. You have created a Console Application and when launching it will search for a static
Mainmethod and that will be executed inside a Console window.You cannot execute arbitrary code when hitting Ctrl + F7.
If you want to execute the code in this class, you need to add some code to your
Mainmethod (which will be executed) to create an instance of this class and execute theGetPortName.Here is some MSDN documentation that shows how a Console Application works.
When you look at your Project properties (right click in the solution explorer on your project and click Properties) you will see an item Startup Object. This points to the class that contains the starting point for your application. Windows will look for a Main method in that class and start running your program from there.
I would not advice moving all your code inside
Main. This will create one big function that will execute all of your logic. For a reasonobly sized program, yourMainmethod would explode and it would be a nightmare to maintain. Partitioning code in objects that fullfill specific goals can help you with building a better maintainble program. Look into the basics of object oriented development to understand how this can help. Here is a link to Wikipedia with some info on Object Oriented Programming.Another thing that’s wrong with your code is that an outer class cannot be protected. You need to change
protected class consolereadintopublic class ConsoleRead(Casing is for readability).