N
N
Nikita M.2020-12-06 18:21:59
.NET
Nikita M., 2020-12-06 18:21:59

C# Why is class instance in var initialized with null?

Hello, can someone explain why in this code:

static ITelegramBotClient botClient;
        static void Main(string[] args)
        {
            botClient = new TelegramBotClient("");
            var bot = botClient.GetMeAsync().Result;
            Console.WriteLine($"Bot started. Bot name: {bot.FirstName}, {bot.Username}");
            botClient.OnMessage += Bot_OnMessage;
            botClient.StartReceiving();
            Console.WriteLine("Press any key to stop bot");
            Console.ReadKey();
            botClient.StopReceiving();


        }
        static async void Bot_OnMessage(object sender, MessageEventArgs e)
        {
            if (e.Message.Text != null)
            {
                Console.WriteLine($"Received message: {e.Message.Text} from {e.Message.Chat.FirstName}");
                Console.WriteLine($"Chat id: {e.Message.Chat.Id}");
                await botClient.SendTextMessageAsync(chatId: e.Message.Chat.Id, text: "Yes bot is working hey");
            }
        }

botClient is not null and works as it should, but if you add var: botClient is always null. I can't get enough of this... Thanks in advance.
var botClient = new TelegramBotClient("");

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Ananiev, 2020-12-06
@unknowndeal

Your botClient is a global variable. When you write var botClient you are declaring a local variable with the same name as the global one. In this case, the global variable remains null.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question