Tuesday, February 4, 2025

Top Level Statements in C#

C# Top-Level Statements vs. Main Method

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 a Main 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. 🚀

Visual Studio Remove Blank spaces

  1. In window, press Ctrl+H (quick replace)
  2. Click "Use regular expressions"
  3. In Find, specify: ^\$\n
  4. leave Replace as blank
  5. Click "Replace All"  All blank lines will be deleted.
Understanding the Regular Expression: ^\s*$\n

This regular expression is used to identify and remove blank lines from text.

  • ^: Matches the beginning of a line. Since we're using the `re.MULTILINE` flag in Python, each line in the text is treated as a separate unit.
  • \s*: Matches zero or more whitespace characters (spaces, tabs, newlines).
  • $: Matches the end of a line.
  • \n: Matches a newline character.

In essence, this regular expression matches a line that:

  1. Starts with the beginning of the line.
  2. Contains zero or more whitespace characters.
  3. Ends with the end of the line.
  4. Is followed by a newline character.

Therefore, it effectively targets and matches blank lines that might contain spaces or tabs.

Thanks to Gemini for the explaination.


Top Level Statements in C#

C# Top-Level Statements vs. Main Method C# Top-Level Statements vs. Main Method In C# 9 and later, you can use ...