Problem with generic list and extension method(C#3.0)

Posted by Newbie on Stack Overflow See other posts from Stack Overflow or by Newbie
Published on 2010-04-28T06:48:26Z Indexed on 2010/04/28 6:53 UTC
Read the original article Hit count: 215

Filed under:

I have an issue. I am making an extension class for a Collection and it is generic.. like

public static class ListExtensions
    {

        public static ICollection<T> Search<T>(this ICollection<T> collection, string stringToSearch)
        {
            ICollection<T> t1=null;           

            foreach (T t in collection)
            {
                Type k = t.GetType();
                PropertyInfo pi = k.GetProperty("Name");
                if (pi.GetValue(t,null).Equals(stringToSearch))
                {
                    t1.Add(t);
                }
            }
            return t1;
        }
    }

But I cannot add items to t1 as it is declared null. Error: object reference not set to an instance of the object.

I am calling the method like

List<TestClass> listTC = new List<TestClass>();

            listTC.Add(new TestClass { Name = "Ishu", Age = 21 });
            listTC.Add(new TestClass { Name = "Vivek", Age = 40 });
            listTC.Add(new TestClass { Name = "some one else", Age = 12 });
            listTC.Search("Ishu");

And the test class is

public class TestClass
    {
        public string Name { get; set; }
        public int Age { get; set; }
    }

Using : (C#3.0) & Framework - 3.5 Thanks

© Stack Overflow or respective owner

Related posts about c#3.0