locked
Extension method must be defined in a non-generic static class RRS feed

  • Question

  • User-1392235324 posted
    using System;
    using System.Collections.Generic;
    using System.Linq;
    
    namespace WebApplication1
    {
        public partial class CsWebForm : System.Web.UI.Page
        {
            protected void Page_Load(object sender, EventArgs e)
            {
                List<string> myList = new List<string>
                    { "hello", "random", "world", "foo", "bar", "bat", "baz" };
    
                foreach (string i in myList)
                {
                    Response.Write(i + "<br/>");
                }
            }
    
                public static IEnumerable<t> Randomize<t>(this IEnumerable<t> target)
                {
                    Random r = new Random();
    
                    return target.OrderBy(x => r.Next());
                }
        }
    }

    The below code works but the result doesn't randomize !

    using System;
    using System.Collections.Generic;
    using System.Linq;
    
    namespace WebApplication1
    {
        public partial class CsWebForm : System.Web.UI.Page
        {
            protected void Page_Load(object sender, EventArgs e)
            {
                List<string> myList = new List<string>
                    { "hello", "random", "world", "foo", "bar", "bat", "baz" };
    
                foreach (string i in myList)
                {
                    Response.Write(i + "<br/>");
                }
            }
        }
    
        public static class CsWebFormExtensions
        {
            public static IEnumerable<t> Randomize<t>(this IEnumerable<t> target)
            {
                Random r = new Random();
    
                return target.OrderBy(x => r.Next());
            }
        }
    }

    Please, how to solve this ?

    Tuesday, November 24, 2015 7:56 AM

Answers

  • User753101303 posted

    Hi,

    You still have to call your extension method. For example :

    IEnumerable<string> myList = new List<string> { "hello", "random", "world", "foo", "bar", "bat", "baz" }.Randomize();

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, November 24, 2015 8:23 AM