locked
Using a variable with the 'is' keyword in C# RRS feed

  • Question

  • Hi,

    I want to create a method to access the for the ASP.NET Session object. Where I could pass 2 parameters to a method respectively the identifier name and the type of the object.

    public object GetSessionData(string propertyName, Type objectType) { if (this.Session[propertyName] != null && this.Session [propertyName] is objectType) {

    } }

    But the above method is wrong because we cannot use the is like that.

    How to perform this ?

    Thanks in advance.


    My blog : http://thuruinhttp.wordpress.com

    Tuesday, December 3, 2013 12:50 PM

Answers

  • One solution is to use Type.Equals method to check type equality.

    public object GetSessionData(string propertyName, Type objectType) 
    { 
        object obj = Session[propertyName];
        
        if (obj != null && obj.GetType().Equals(objectType))
        {
        } 
    }

    • Proposed as answer by Stefan Hoffmann Tuesday, December 3, 2013 1:40 PM
    • Marked as answer by Thuru VMVP Wednesday, December 4, 2013 12:58 PM
    Tuesday, December 3, 2013 1:23 PM

All replies

  • One solution is to use Type.Equals method to check type equality.

    public object GetSessionData(string propertyName, Type objectType) 
    { 
        object obj = Session[propertyName];
        
        if (obj != null && obj.GetType().Equals(objectType))
        {
        } 
    }

    • Proposed as answer by Stefan Hoffmann Tuesday, December 3, 2013 1:40 PM
    • Marked as answer by Thuru VMVP Wednesday, December 4, 2013 12:58 PM
    Tuesday, December 3, 2013 1:23 PM
  • Hi thuruv,

    Try to use the .GetType() method for instances and typeof() for classes instead. For example:

    this.Session [propertyName].GetType() == objectType
    Tuesday, December 3, 2013 1:23 PM
  • Generally ASP.NET question should be asked in the ASP Forum, you get better answers there:http://forums.asp.net/

    But at it's core the session is little more then a Dictionary<String, Object> so we can still answers stuff about it.

    Okay, the big question here is why are you not certain what type a specific Session Object is? I mean put it in there. Why would you store different types under the same name? That sounds like it is not a good design.
    What is the problem you think you solve with this design?

    If you have an unknown amount of Varriables, it is usually best to just store them into an array, list, dictionary or the like and put that Collection into the Session. Don't go and create Property Names in code, they should be hardcoded and you should never use the same name for different types.


    Let's talk about MVVM: http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/b1a8bf14-4acd-4d77-9df8-bdb95b02dbe2 Please mark post as helpfull and answers respectively.

    Tuesday, December 3, 2013 1:34 PM