CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 5 of 5
  1. #1
    Join Date
    Oct 2011
    Posts
    3

    Question Casting objects to their given types

    I have a problem where I need to compare two objects but of course you can't do this with ordinary objects. I figure I need to cast the objects to their respective types first and then compare them. I don't really know what the object types will be so I can't just tell myself in code. Really, it seems like I need a cast function that I can pass the object type into and have it cast the object. Here is a code-snipit:

    Code:
            public string FnLessThan(FSFunction fn)
            {
                // LessThan( val1, val2 )
                object v1, v2;
                Object val1 = parser.FindObject(fn.GetParm(0));
                if (val1 != null)
                    v1 = val1.Obj;
                else
                {
                    v1 = new Double();
                    v1 = Convert.ToDouble(fn.GetParm(0));
                }
                Object val2 = parser.FindObject(fn.GetParm(1));
                if (val2 != null)
                    v2 = val2.Obj;
                else
                {
                    v2 = new Double();
                    v2 = Convert.ToDouble(fn.GetParm(1));
                }
                if (v1 < v2)
                    return "True";
                return "False";
            }
    The error is at the 'if(v1<v2)'. It says something like you can't do this with objects.

    Thanks,
    I'm using .NET 4.0

  2. #2
    Arjay's Avatar
    Arjay is offline Moderator / EX MS MVP Power Poster
    Join Date
    Aug 2004
    Posts
    13,490

    Re: Casting objects to their given types

    Assuming you are only ever comparing doubles, then just declare the objects as doubles. Something like:
    Code:
    public bool FnLessThan(FSFunction fn)
    {
      double v1, v2;
    
      try
      {
         v1 = Convert.ToDouble(fn.GetParm(0));
         v2 = Convert.ToDouble(fn.GetParm(1));
      }
      catch( Exception )
      {
        return false;
      }
    
      return v1 < v2 ? true : false;
    }
    If you need to compare other types, you might use a generic method
    Code:
    public bool FnLessThan<T1, T2>(FSFunction fn)
      Where T1 : Tbase
      Where T2 : Tbase
    {
      T1 v1;
      T2 v2;
    
      try
      {
         v1 = (T1) Convert.ChangeType(fn.GetParm(0), typeof( T1 ) );
         v2 = (T2) Convert.ChangeType(fn.GetParm(1), typeof( T2 ) );
      }
      catch( Exception )
      {
        return false;
      }
    
      return 0 > v1.CompareTo( v2 ) ? true : false;
    }
    I've constrained the above method to work only from types derived from Tbase (which you'll have to define). You also need to implement the IComparable in Tbase and override the CompareTo() method in each derived class. I don't expect the code snippet above to work right out of the box, but hopefully it will give you some ideas.

  3. #3
    Join Date
    May 2007
    Posts
    1,546

    Re: Casting objects to their given types

    I have a problem where I need to compare two objects
    The solution is simples!

    Code:
    object first = GetFirstObject ();
    object second = GetSecondObject ();
    
    if (first is IComparable)
        return ((IComparable) first).CompareTo (second) < 0;
    If you know what type they are supposed to be you could also check for the generic IComparable<T> interface and potentially use that, but the non-generic one is probably your best bet.

    If the objects don't support the IComparable interface the only way to use '>' or '<' to compare the items is to actually cast them in code to the correct type as follows:

    Code:
    object first = GetFirstObject ();
    object second = GetSecondObject ();
    
    if (first is MyClass && second is MyClass)
        return (MyClass)first < (MyClass) second;
    else
        throw new Exception ("Cannot compare");
    www.monotorrent.com For all your .NET bittorrent needs

    NOTE: My code snippets are just snippets. They demonstrate an idea which can be adapted by you to solve your problem. They are not 100% complete and fully functional solutions equipped with error handling.

  4. #4
    Join Date
    Oct 2011
    Posts
    3

    Unhappy Re: Casting objects to their given types

    The problem with using typeof, ChangeType and anything else like that is that this type that I'm trying to cast my objects to is unknown at compile time. It is not declared anywhere in my project so I cannot cast it using the normal means. I found an article on DynamicCasting using Reflection but even that doesn't help because I don't have the actual type of the object to cast it to. I have the Type, but that is different from having the type declared in my code. I'm wondering if the only solution is to force all objects to have a base type that they are derived from so at least I have something to cast them to. Otherwise, there seems to be no way I can do this in C#. Am I wrong?

  5. #5
    Join Date
    Oct 2011
    Posts
    3

    Re: Casting objects to their given types

    Thanks, IComparable seems to be the ticket.

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured