2

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.

Kamil Budziewski
  • 22,699
  • 14
  • 85
  • 105
AllDayPiano
  • 414
  • 1
  • 4
  • 20
  • 1
    You generally want a single `Random` object to pull random numbers from, so in this case you might want your `new Random` to be in a constructor or static property, then you only need to `rnd.Next` to get your next random number. – crashmstr Oct 22 '15 at 12:25

2 Answers2

1

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.

Kamil Budziewski
  • 22,699
  • 14
  • 85
  • 105
0

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.

Community
  • 1
  • 1
Sinatr
  • 20,892
  • 15
  • 90
  • 319