The thing is I need to pass a random variable to optional parameter. Anyone? :)
Something like this:
static void Creature(string optionalParam = randomVariable) {}
The thing is I need to pass a random variable to optional parameter. Anyone? :)
Something like this:
static void Creature(string optionalParam = randomVariable) {}
Optional parameters are compile time constants, so you can't have a random (runtime generated) value as an optional parameter value.
What you could do, as @madreflection eludes to, is create 2 overloaded methods: one that will accept the randomValue you pass it and second one without that parameter that generates a Random number and then calls the first overload, passing that random value along. Make sense?
You can only do this with overloads
class Foo
{
static Random rng = new Random();
static string RandomString()=> $"A{rng.Next(0,1000)}";
static void Creature() => Creature(RandomString())
static void Creature(string argument) {}
}
You can do the below with [optional] keyword. by default optionalParam value will be Null if you do not pass anything else it will hold the passing value. I hope it will clear about optional parameter. Reference: https://www.geeksforgeeks.org/different-ways-to-make-method-parameter-optional-in-c-sharp/