1

I'm trying to create a function that either returns the first element in an enumerable or the appropriate type of null. I would think class and struct are disjoint, but these two functions can't seem to exist in the same namespace. Why?

static T? TryFirst<T>(IEnumerable<T> b) where T : struct
{
    return b.Any() ? b.First() : new T?();
}
static T TryFirst<T>(IEnumerable<T> b) where T : class
{
    return b.Any() ? b.First() : null;
}
Carbon
  • 3,828
  • 3
  • 24
  • 51

1 Answers1

2

It's because compiler will not be able to differentiate them.

You're creating same functions with same arguments.
where statement only states what generic types you can pass into this function but function definition itself is still the same for the compiler.

I recommend doing this:

static T? TryFirstStruct<T>(IEnumerable<T> b) where T : struct
{
    return b.Any() ? b.First() : new T?();
}

static T TryFirstObject<T>(IEnumerable<T> b) where T : class
{
    return b.Any() ? b.First() : null;
}

Also, if compiler would allow this behavior then programmer who's using your code next is going to get two same functions that receive and return same things.

Problems are:

  • Your colleague will be pretty confused about it.
  • When you'll use var keyword it will not be able to understand what value is going to be returned back to you.
  • You'll have to use dynamic keyword and check type by yourself. Therefore you'll increase your code by a few times, slow down methods and generally make it unreadable.
Vyacheslav
  • 559
  • 2
  • 11