Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to exclude IEnumerable and primitive types from Object parameter?

Tags:

c#

generics

I have this extension method:

public static T Foo<T>(this Object current) where T : class, new()
{
    ...
}

Is it possible to exclude primitive types and IEnumerable interface from "this Object current"?

Editet My question is not a duplicate, because in suggested question problem is in collision of parameters between overload methods. Author asked, is it possible to exclude String type from one of methods to give abbility for another method to pick it. And helpful answer for that question is not helpful for me

like image 687
Vitaliy Avatar asked Dec 29 '17 10:12

Vitaliy


2 Answers

No. You cannot. There is no generic type constraint available for such things. An option could be to specify a method which you mark Obsolete:

[Obsolete("Do not use with IEnumerable!", true)]
public static T Foo<T>(this IEnumerable current) where T : class, new()
{
    ...
}

You do understand the list would get endless. Another option would be a Roslyn code analyzer which checks your code for disallowed combinations, but that might be overkill.

like image 113
Patrick Hofman Avatar answered Sep 19 '22 00:09

Patrick Hofman


Patrick Hofman allready gave the correct answer, but i want to offer another possibility to deal with that problem

Possible Approach

As Evk allready stated in his comment.

Depending on how many types you want to allow, you could explicitly allow these types.

Bad Approach

I don't really like the Feeling of adding obsolete Tags to Enforce certain types on Genericmethods.

Warning: Do not use the following approach!

You could must not check for the type and throw an exception.

/// <summary>
/// 
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="current">Dont throw in IENumerables !</param>
/// <returns></returns>
public static T Foo<T>(this Object current) where T : class, new() {
        if (current is IEnumerable) {
            throw new NotSupportedException($"Type  {current.GetType()} is not supported!");
        }
        //...
}

Why is this a bad approach? -> This could result in crashing your application.

Why is Patricks approach better? -> His approach results in a compiler warning/error, which is better than having an Application crash in production.

like image 42
Tobias Theel Avatar answered Sep 20 '22 00:09

Tobias Theel