2

I would like to be able to determine the type of an object and then cast that object into what it should be. I'll do my best to explain. The code below DOES NOT work, but it shows what I am looking to achieve. I need to return the size of an unknown object type; could be a button, a panel, form, etc.

public static void Draw(object AnimateObject) { try { // Set the starting coordinants for our graphics drawing int y = 0; int x = 0; // Set the end coordinants for our graphics drawing int width = AnimateObject.Size.Width; int height = AnimateObject.Size.Height; // More graphics related stuff here... } } 

Normally I could just cast the object into what it should be and be done with it, but once the 'Unknown object' part came up, I've somewhat hit a dead end. I'm sure I could overload the thing a million times and make it find the right type, but I'm hoping there is a more sensible way to do it.

4
  • 1
    Seems like you need dynamic not object. Commented Dec 6, 2013 at 20:44
  • Is there a common parent to all these types that does have a Size? That is what polymorphism is all about. Commented Dec 6, 2013 at 20:44
  • You could try with dynamic. It will move all checkes from compile time to runtime. Or find a common type which all other derives from (or interface then implement) and create generic method. Commented Dec 6, 2013 at 20:44
  • @Candide dynamic fixed it! I will accept as answer if posted. Commented Dec 6, 2013 at 21:04

2 Answers 2

2

Have all one million of those types implement an interface that has a Size property, and then type the parameter to be of that interface, rather than doing compile time checks of the type constantly to try to support anything that could possibly have a size.

If Some of the objects can't be modified to implement the interface, consider adding an extra delegate as a parameter to select the size by doing something like this:

public static void Draw<T>(T AnimateObject, Func<T, Size> sizeSelector) 

You can then use that delegate inside of the method to access the object's size.

The caller can then write something like this:

Draw(square, obj => obj.Size); 
Sign up to request clarification or add additional context in comments.

Comments

1

Since the type of AnimateObject is not known you could rely on the dynamic runtime:

public static void Draw(dynamic AnimateObject) { try { // Set the starting coordinants for our graphics drawing int y = 0; int x = 0; // Set the end coordinants for our graphics drawing int width = AnimateObject.Size.Width; int height = AnimateObject.Size.Height; // More graphics related stuff here... } catch { /* type doesn't respond as expected */ } } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.