C# Top-Level Statements vs. Main Method
In C# 9 and later, you can use top-level statements, which eliminate the need for explicitly defining a Main
method. Your code uses this feature, so the Main
method is not required.
Why is Main
Not Required?
- Starting from C# 9, you can write top-level statements directly in a
.cs
file, and the compiler will implicitly generate aMain
method. - This feature is designed to make simple programs (like console applications) more concise.
How It Works:
- The compiler automatically wraps the code inside a generated
Main
method. - Your program starts executing from the first statement.
- Any
await
statements require an async context, which is automatically handled.
If Using Older C# Versions:
If you're using C# 8 or earlier, or if you prefer the traditional structure, you would need to explicitly define Main
like this:
using System;
using System.Text;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using MQTTnet;
using MQTTnet.Client;
using MQTTnet.Protocol;
class Program
{
static async Task Main()
{
Console.WriteLine("Starting MQTT Client...");
var mqttFactory = new MqttFactory();
var mqttClient = mqttFactory.CreateMqttClient();
var mqttClientOptions = new MqttClientOptionsBuilder()
.WithTcpServer("broker.mqtt-dashboard.com", 1883)
.WithCleanSession()
.Build();
double Temperature = -5;
double WindSpeed = 10;
var Rand = new Random();
mqttClient.ConnectedAsync += async e =>
{
Console.WriteLine("Successfully connected to the MQTT broker.");
while (true)
{
double currentTemperature = Math.Round((Temperature + Rand.NextDouble()), 3);
double currentWindSpeed = Math.Round((WindSpeed + Rand.NextDouble()), 3);
var message = new MqttApplicationMessageBuilder()
.WithTopic("LRLBTopic")
.WithPayload(Encoding.UTF8.GetBytes(JsonSerializer.Serialize(new
{
Temperature = currentTemperature,
WindSpeed = currentWindSpeed,
})))
.WithQualityOfServiceLevel(MqttQualityOfServiceLevel.AtLeastOnce)
.Build();
await mqttClient.PublishAsync(message);
Console.WriteLine("Message published to topic: LRLBTopic");
Thread.Sleep(2000);
}
};
mqttClient.DisconnectedAsync += e =>
{
Console.WriteLine("Disconnected from the MQTT broker.");
return Task.CompletedTask;
};
try
{
await mqttClient.ConnectAsync(mqttClientOptions);
}
catch (Exception ex)
{
Console.WriteLine($"Error connecting to the MQTT broker: {ex.Message}");
return;
}
Console.WriteLine("Press any key to exit...");
Console.ReadKey();
await mqttClient.DisconnectAsync();
}
}
Summary:
- C# 9+:
Main
is optional (uses top-level statements). - C# 8 or earlier:
Main
is required. - For explicit structure: You can still define
Main
if you prefer.
Your code will work fine as long as you are using C# 9 or later in your project. 🚀
No comments:
Post a Comment