none
Cannot using generic in extension method RRS feed

  • Question

  • I want to write 1 extension method,it's purpose is convert 1 IEnumerable<T> to 1 ObservableCollection<T>, but error :

    Error    5    The type or namespace name 'T' could not be found (are you missing a using directive or an assembly reference?)

    Here is my code :

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Collections.ObjectModel;
    using System.Data;
    
    namespace BookStore.Helper
    {
        public static class ExtensionMethods
        {
            public static ObservableCollection<T> ToObservableCollection(this IEnumerable<T> source)
            {
                ObservableCollection<T> target = new ObservableCollection<T>();
                foreach (T item in source)
                    target.Add(item);
                return target;
            }
    
        }
    }
    
    

    Pls help me!

     

    Friday, November 11, 2011 8:59 AM

Answers

  • ObservableCollection have constructor with IEnumerable<T> parameters, so that code can be shortened to:

    public static class ExtensionMethods
    {
        public static ObservableCollection<T> ToObservableCollection<T>(this IEnumerable<T> source)
        {
            ObservableCollection<T> target = new ObservableCollection<T>(source);
            return target;
        }
    }
    


    • Proposed as answer by MusicDemon Sunday, November 13, 2011 3:05 PM
    • Marked as answer by Lie YouModerator Friday, November 18, 2011 1:53 AM
    Saturday, November 12, 2011 9:13 PM

All replies

  • public static class ExtensionMethods
        {
            public static ObservableCollection<T> ToObservableCollection<T>(this IEnumerable<T> source)
            {
                ObservableCollection<T> target = new ObservableCollection<T>();
                foreach (T item in source)
                    target.Add(item);
                return target;
            }
    
        }
    

    The function doesn't have a type parameter. :)
    Regards, MusicDemon
    Friday, November 11, 2011 10:48 AM
  • ObservableCollection have constructor with IEnumerable<T> parameters, so that code can be shortened to:

    public static class ExtensionMethods
    {
        public static ObservableCollection<T> ToObservableCollection<T>(this IEnumerable<T> source)
        {
            ObservableCollection<T> target = new ObservableCollection<T>(source);
            return target;
        }
    }
    


    • Proposed as answer by MusicDemon Sunday, November 13, 2011 3:05 PM
    • Marked as answer by Lie YouModerator Friday, November 18, 2011 1:53 AM
    Saturday, November 12, 2011 9:13 PM