user272671
user272671

Reputation: 657

Format of Generic methods with generic returns

I would like to implement a function that returns a value of the type it is operating on. How do I accomplish this please?

Example 1:

static T Swap<T>(ref T lhs, ref T rhs)
{
    T temp;
    temp = lhs;
    lhs = rhs;
    rhs = temp;

    return <T> temp;
}

Example 2:

public override T GetRandom()
{
    return  (T)_random.Next(_min, _max);
}

Upvotes: 0

Views: 103

Answers (2)

jflood.net
jflood.net

Reputation: 2456

it makes no sense to make this generic:

public override T GetRandom()
{
     return  (T)_random.Next(_min, _max);
}

what is meant by random "T"? Suppose T is of type "Person", what is meant by returning random Person? There just doesn't seem to be any logic in having a generic GetRandom method.

If you want an integer just specify int as the return type.

public override int GetRandom()
{
    return  _random.Next(_min, _max); 
}

Upvotes: 0

Marc Gravell
Marc Gravell

Reputation: 1064104

Since both the return-type and the variable-type are already T, this is just:

return temp;

Alternatively, to cast (but this is not needed here):

return (T) temp;

Actually, though, IMO a "swap" should have void return!

Upvotes: 7

Related Questions