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 1111243
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 17, 20262026-05-17T02:30:59+00:00 2026-05-17T02:30:59+00:00

I have written an extension method in csharp for an MVCContrib Html helper and

  • 0

I have written an extension method in csharp for an MVCContrib Html helper and was surprised at the form of the generic constraint, which on the face of it seems to circularly reference itself through the type parameter.

This being said the method compiles and works as desired.

I would love to have someone explain why this works and if a more intuitive intuitive syntax exists and if not if anyone know why?

Here is the compiling and function code but I have removed the List of T example as it clouded the issue. as well as an analogous method using a List<T>.

namespace MvcContrib.FluentHtml 
{
  public static class FluentHtmlElementExtensions
  {
    public static TextInput<T> ReadOnly<T>(this TextInput<T> element, bool value)
        where T: TextInput<T>
    {
        if (value)
            element.Attr("readonly", "readonly");
        else
            ((IElement)element).RemoveAttr("readonly");
        return element;
    }
  }
}

    /*analogous method for comparison*/
    public static List<T> AddNullItem<T>(this List<T> list, bool value) 
        where T : List<T>
    {
        list.Add(null);
        return list;
    }

In the first method the constraint T : TextInput<T> seems to all intents and purposes, circular. However if I comment it out I get a compiler error:

“The type ‘T’ cannot be used as type parameter ‘T’ in the generic type or method ‘MvcContrib.FluentHtml.Elements.TextInput<T>’.
There is no boxing conversion or type parameter conversion from ‘T’ to ‘MvcContrib.FluentHtml.Elements.TextInput<T>’.”


and in the List<T> case the error(s) are:

“The best overloaded method match for ‘System.Collections.Generic.List.Add(T)’ has some invalid arguments
Argument 1: cannot convert from ‘<null>’ to ‘T'”

I could imagine a more intuitive definition would be one that includes 2 types, a reference to the Generic Type and a reference to the Constraining Type eg:

public static TextInput<T> ReadOnly<T,U>(this TextInput<T> element, bool value) 
    where U: TextInput<T>

or

public static U ReadOnly<T,U>(this U element, bool value) 
    where U: TextInput<T>

but neither of these compile.

  • 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-17T02:31:00+00:00Added an answer on May 17, 2026 at 2:31 am

    UPDATE: This question was the basis of my blog article on the 3rd of February 2011. Thanks for the great question!


    This is legal, it is not circular, and it is fairly common. I personally dislike it.

    The reasons I dislike it are:

    1. It is excessively clever; as you’ve discovered, clever code is hard for people unfamiliar with the intricacies of the type system to intuitively understand.

    2. It does not map well to my intuition of what a generic type "represents". I like classes to represent categories of things, and generic classes to represent parameterized categories. It is clear to me that a "list of strings" and a "list of numbers" are both kinds of lists, differing only in the type of the thing in the list. It is much less clear to me what "a TextInput of T where T is a TextInput of T" is. Don’t make me think.

    3. This pattern is frequently used in an attempt to enforce a constraint in the type system which is actually not enforcable in C#. Namely this one:

      abstract class Animal<T> where T : Animal<T>
      {
          public abstract void MakeFriends(IEnumerable<T> newFriends);
      }
      class Cat : Animal<Cat>
      {
          public override void MakeFriends(IEnumerable<Cat> newFriends) { ... }
      }
      

    The idea here is "a subclass Cat of Animal can only make friends with other Cats."

    The problem is that the desired rule is not actually enforced:

    class Tiger: Animal<Cat>
    {
        public override void MakeFriends(IEnumerable<Cat> newFriends) { ... }
    }
    

    Now a Tiger can make friends with Cats, but not with Tigers.

    To actually make this work in C# you’d need to do something like:

    abstract class Animal 
    {
        public abstract void MakeFriends(IEnumerable<THISTYPE> newFriends);
    }
    

    where "THISTYPE" is a magical new language feature that means "an overriding class is required to fill in its own type here".

    class Cat : Animal 
    {
        public override void MakeFriends(IEnumerable<Cat> newFriends) {}
    }
    
    class Tiger: Animal
    {
        // illegal!
        public override void MakeFriends(IEnumerable<Cat> newFriends) { ... }
    }
    

    Unfortunately, that’s not typesafe either:

    Animal animal = new Cat();
    animal.MakeFriends(new Animal[] {new Tiger()});
    

    If the rule is "an animal can make friends with any of its kind" then an animal can make friends with animals. But a cat can only make friends with cats, not tigers! The stuff in the parameter positions has got to be valid contravariantly; in this hypothetical case we’d be requiring covariance, which isn’t going to work.

    I seem to have digressed somewhat. Returning to the subject of this curiously recurring pattern: I try to only use this pattern for common, easily understood situations like the ones mentioned by other answers:

    class SortedList<T> where T : IComparable<T>
    

    That is, we need every T to be comparable to every other T if we have any hope of making a sorted list of them.

    To actually be flagged as circular there has to be a bona-fide circularity in dependencies:

    class C<T, U> where T : U where U : T
    

    An interesting area of type theory (that at present the C# compiler handles poorly) is the area of non-circular but infinitary generic types. I have written an infinitary type detector but it did not make it into the C# 4 compiler and is not a high priority for possible hypothetical future versions of the compiler. If you’re interested in some examples of infinitary types, or some examples of where the C# cycle detector messes up, see my article on that:

    https://ericlippert.com/2008/05/07/covariance-and-contravariance-part-11-to-infinity-but-not-beyond/

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

Sidebar

Related Questions

I have written an extension method for string manipulation. I'm confused what should I
I am writing some unit tests for an extension method I have written on
I have a class library with some extension methods written in C# and an
I have written some code in my VB.NET application to send an HTML e-mail
I have written a ruby script which opens up dlink admin page in firefox
I have written an AppleScript which when supplied with a Windows network link, will
I have an extension method with the following signature: public static Expression<Func<T, bool>> And<T>(this
I have written a custom dialog (form) that I can use in a C#
I have written an AIR Application that downloads videos and documents from a server.
I have written a site in Prototype but want to switch to jQuery. Any

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.