Answer the question
In order to leave comments, you need to log in
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");
}
}
var botClient = new TelegramBotClient("");
Answer the question
In order to leave comments, you need to log in
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 questionAsk a Question
731 491 924 answers to any question