Reputation: 422
I tried to figure it out but I don't get a clue on either how to pass a result of a new instance of a class to a function call or if this is even possible.
If I wan't to pass a random number, I'll have to create it first:
int n = 0;
Random rnd = New Random();
int m = rnd.Next(0, n);
MyClass.MyFunction(MyValue1, m);
Actually, this is 4 lines of code. However, as a newbie to c# I've already seen a lot and want to know, if there is a shorter version of this. Some pseudo code:
MyClass.MyFunction(MyValue1, Random rnd = new Random() {rnd.Next(0, n); return});
Is this somehow possible? I thought I have seen something like this but can't find anything about it.
Upvotes: 2
Views: 102
Reputation: 21999
I'll simply leave this here
MyClass.MyFunction(MyValue1, ((Func<int>)(() =>
{
int n = 0;
var rnd = new Random();
return rnd.Next(0, n);
}))());
P.S.: it compiles and works.
As @crashmstr commented, it's actually not a good idea specifically to Random
. For single random value is ok, but for series of random numbers you don't want to create new instance every time or your numbers will become not so random.
Upvotes: 0
Reputation: 23087
You can call Next
just after new Random()
MyClass.MyFunction(MyValue1, new Random().Next(0,n));
new Random()
will create object of Random
and on it you can call Next()
. So it's possible to call it inline without need to store Random
before.
Upvotes: 1