Hi
I am getting error - A Static readonly field cannot be assigned except in a static construcor or a variable initializer.
C#
static async Task Main(string[] args)
{
_duration = TimeSpan.Zero;
_random = new Random();
await Start();
}Thanks

Amit MohantyRank #112 · 20K reputationPosted Apr 8, 2024, 8:13 AM EDT
You're trying to assign a value to a static readonly field (_duration or _random) outside of a variable initializer or a static constructor. This is not allowed because readonly fields can only be assigned a value either at the time of declaration or within a static constructor.
So you can use a static constructor to assigned values (_duration or _random) dynamically at runtime or remove the readonly modifier from the fields.
Static constructor:
static readonly TimeSpan _duration; static readonly Random _random; static Program() { _duration = TimeSpan.Zero; _random = new Random(); } static async Task Main(string[] args) { await Start(); }Remove the readonly:
static TimeSpan _duration; static Random _random; static async Task Main(string[] args) { _duration = TimeSpan.Zero; _random = new Random(); await Start(); }