N
N
nordwind20132018-07-20 08:52:09
ASP.NET
nordwind2013, 2018-07-20 08:52:09

Why does it return null when using a generic class object method?

There is a generic class that describes repositories. Here is the code

public class BaseServices<T> : IBaseService<T> where T : BaseEntity, new()

    {

        public List<T> AllItem = new List<T>();

        public bool Delete(int id) 
        {
            bool b = false;

            foreach (var a in AllItem)
            {
                if (a.Id == id)
                {
                    AllItem.Remove(a);

                    b = true;
                }
            }

            return b;
        }

        public T Get(int id)
        {
            T b = null;

            foreach (var a in AllItem)
            {
                if (a.Id == id)
                {
                    b = a;
                    return b;
                }
            }

            return b;
        }

        public object GetAll() 
        {
            object b = null;

            foreach (var a in AllItem)
            {
                b = a;
                return b;
            }

            return b;
        }

        public bool Save(T entity)
        {
            entity = new T();

            AllItem.Add(entity);

            return true;
        }
    }

And there is a test
List<AccountModel> Accounts = new List<AccountModel>();

        private BaseServices<AccountModel> AccountBS = new BaseServices<AccountModel>();

        Random rnd = new Random();

        public void Repletion()
        {
            for (int index = 0; index < 100; ++index)
            {
                AccountBS.AllItem[index] = new AccountModel();

                AccountBS.AllItem[index].Id = index;

            }

        }

    [TestMethod]
        public void GetTest()
        {
            int SomeId = rnd.Next(100);

            AccountModel result = AccountBS.Get(SomeId);

            Assert.IsNotNull(result);
        }
    }

For some reason result = null. Please tell me.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
G
Griboks, 2018-07-20
@nordwind2013

The list is empty. The default value is null. So he brings it back.
You forgot to call Repletion to initialize the base.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question