Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 3272394
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 17, 20262026-05-17T18:49:17+00:00 2026-05-17T18:49:17+00:00

Let’s say I have the following method: public static int CountNonNullMembers<T>(this IEnumerable<T> enumerable) {

  • 0

Let’s say I have the following method:

public static int CountNonNullMembers<T>(this IEnumerable<T> enumerable)
{
    if (enumerable == null) throw new ArgumentNullException("enumerable");
    int count = 0;
    foreach (var x in enumerable)
    {
        if (x != null) count++; 
    }
    return count;
}

And I have these 3 arrays::

var ints = Enumerable.Range(0,10).ToArray();
var nullableInts = Array.ConvertAll(ints,x=>x as int?);
var strings = Array.ConvertAll(ints,x => x.ToString());

I wrote a little function to do a loop and time it for a million iterations. Applying it to ints and strings, it finishes in about 100 ms on my machine. For nullableInts, it takes 2.5 seconds.
As I understand the check for null on int doesn’t make sense, so the compiler has a different template for non-nullable struct types, that removes null checks. But Nullable<T> does not have a template that converts the null check to x.HasValue. If I have an unconstrained function, how can I do a null check that will perform well? I can’t use EqualityComparer<T>, as null might not be a member of T as there is no constraint.

Also it’s impossible to have overloads that differ by constraint, so I can’t, say, have one for structs, one for Nullable<T>, and one for classes.

The caller of the method is non-constrained. This is just an example (not the actual method); the method calling is non-constrained. I need to do some work against non-null members, and it’s a generic method. I suppose I could write a version that doesn’t do the check vs one that does (and consequently has a different signature), but it’s seems very ugly and unneeded.

Also, the extension method .Count inexplicably performs horribly for NullableInts and strings, (equally bad), so it really isn’t the right approach. This might be the delegate invocation, but I doubt it. Using the UnboxT style method of Check<T>.IfNull performs a lot better.
Okay, really weird switching the body of the count to this performs great:

    public static int CountNonNullMembers<T>(this IEnumerable<T> enumerable)
    {
        return enumerable.Count(Check<T>.IfNull.Invoke);
    }

Why?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-17T18:49:17+00:00Added an answer on May 17, 2026 at 6:49 pm

    Using the UnboxT approach works. But I’d also like something that doesn’t require creating a static type::

    public static class Check<T>
    {
                public static readonly Predicate<T> IfNull = CreateIfNullDelegate();
                private static bool AlwaysFalse(T obj)
                {
                    return false;
                }
    
                private static bool ForRefType(T obj)
                {
                    return object.ReferenceEquals(obj, null);
                }
    
                private static bool ForNullable<Tu>(Tu? obj) where Tu:struct
                {
                    return !obj.HasValue;
                }
                private static Predicate<T> CreateIfNullDelegate()
                {
                    if (!typeof(T).IsValueType)
                        return ForRefType;
                    else
                    {
                        Type underlying;
                        if ((underlying = Nullable.GetUnderlyingType(typeof(T))) != null)
                        {
                            return Delegate.CreateDelegate(
                                typeof(Predicate<T>),
                                typeof(Check<T>)
                                    .GetMethod("ForNullable",BindingFlags.NonPublic | BindingFlags.Static)
                                        .MakeGenericMethod(underlying)
                            ) as Predicate<T>;
                        }
                        else
                        {
                            return AlwaysFalse;
                        }
                    }
                }
            }
    

    Using this approach everything performs about the same. Strings performs worse, but not so much worse than everything else.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Let's say you have a class called Customer, which contains the following fields: UserName
Let's say I have the following code: Sub TestRangeLoop() Dim rng As Range Set
Let's say I'm building a data access layer for an application. Typically I have
Let's say we have a simple function defined in a pseudo language. List<Numbers> SortNumbers(List<Numbers>
Let's say I have a drive such as C:\ , and I want to
Let's say that we have an ARGB color: Color argb = Color.FromARGB(127, 69, 12,
Let's say you have some products which have 2 fields, a description and a
Let's say I have a property foo defined in my parent POM. Is it
Let's say i have an android device that has some extra buttons on it,
Let us assume I have two classes: class Base{}; class Derived: public Base{}; none

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.