1

If i have this class:

    public class CacheClass
    {
        public string UserID { get; set; }
        public List<string> TabId { get; set; }
        public List<string> State { get; set; }
        public List<string> CanAdmin { get; set; }
    }

Then i add value to class and add to cache. I assign to my var type variable cache value:

    var k = System.Web.HttpContext.Current.Cache[objUserInfo.UserID.ToString()];

So, how i can get foreach loop with var k and get all value?

2 Answers 2

6

As you will see k is an object (hover over var), since the Cache dictionary isn't strongly typed. The compiler doesn't know the actual type is CacheClass. So step 1 is to cast it. I would prefer to use as since it won't throw an exception if casting fails:

var k = System.Web.HttpContext.Current.Cache[objUserInfo.UserID.ToString()] as CacheClass;

Using as does require you to to do a null-check to make sure the cast went okay:

if (k != null)
{
    foreach (string x in k.State)
    {  }
}
Sign up to request clarification or add additional context in comments.

7 Comments

But then i try assign to var k with as CacheClass I always get null. But without as CacheClass i get correct value.
How and where do you save it then? Are you sure the key still matches?
Its testing data. Iam saving like that List<string> temp1 = List<string>(); ... temp1.Add("tabid");...A.TabId=temp1;...System.Web.HttpContext.Current.Cache[objUserInfo.UserID.ToString()] = a; var j = System.Web.HttpContext.Current.Cache[objUserInfo.UserID.ToString()] as CacheList; After button click.
I think you are assigning that one to the cache, aren't you?
CacheClass a = new CacheClass(); Yes one.
|
2

You are probably missing the cast

var k = System.Web.HttpContext.Current.Cache[objUserInfo.UserID.ToString()] as CacheClass;
foreach(var state in k.State) {
    // ...
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.