-1

using these classes

public class Parent
{
   public int parentInt;
}

public class Child: Parent
{
   public string childString;

   public Child(string passedString, int passedInt)
   {
       childString = passedString
       parentInt = passedInt
   }     
}

I want to write a function that does stuff like this:

public static void DoSomething(Parent passedParent, Type passedChildType)
{
    ScreenRecorder.Start()
    //print all of parents properties
    //print all of the specific child's properties if possible

}

I want this function to be able to handle any type of child I create in the future, How can I make it so that I can dynamically rebuild the child's properties inside the function?

Here is an example of the method being called:

public static int dostuff(string s)
{
    int functionReturnValue = 0;

    switch (s)
    {
        case "":
            functionReturnValue = 0;
            break;
        case "7/8":
            functionReturnValue = 14;
            break;
        case "15/16":
            functionReturnValue = 15;
            break;
        default:
            Child ex = new Child("Blue", 1);
            Library.Handler.Process(ex, typeof(Child));
            break;
    }
    return functionReturnValue;
}

What can I pass in or do inside the Dosomething method to rebuild the child object attributes?

Jeremy Lin
  • 400
  • 3
  • 13
  • 3
    Exceptions show that an exceptional case has happened. They should be thrown where they happen. – Magus Feb 25 '14 at 17:07
  • 1
    Agree with Magus. Throw the exception. You can call your function in your `catch` handler. You won't have to "rebuild" the `Exception` object as you'll get the original passed to you & all `Exception` classes descend from `Exception`. That's what polymorphism is for. – Tony Vitabile Feb 25 '14 at 17:09
  • What if I later decide that I want my program to try and handle it gracefully and not tell the user about it and hope things just keep working? As opposed to how it is now where I want it to blow up. How can I make this behaviour dynamic? – Jeremy Lin Feb 25 '14 at 17:09
  • You should look into Aspect oriented programming. You could pass all your methods through a handler and manage your exception types in one place. As for that last comment, you never want it to blow up. Catch the error and re-throw it if you want, but handle it first. – crthompson Feb 25 '14 at 17:11
  • You should do that in the caller. Exceptions are the right way to say something broke. Handle them if you know the specific exception, but otherwise you really need to know something went wrong, and should not allow the program to continue running in an invalid state. Only attempt to recover from exceptions you specifically know about, and remember that some, you can't. – Magus Feb 25 '14 at 17:11
  • 1
    Please, don't turn exceptions into error codes. Exceptions were invented to replace error codes, don't downgrade them. – Dennis Feb 25 '14 at 17:14
  • In regards to your edit, we aren't the ones who should replace the exception with some other object. If you want to log information about an invalid match, go head. **Do not** use exceptions for that. While your question may not be about system architecture, don't expect us to ignore flagrant disregard for fundamental .Net concepts. You need some kind of message class, so you should probably design one. – Magus Feb 25 '14 at 17:56

2 Answers2

0

To answer the question that is actually being asked. Yes you can "rebuild" an object on the other side.

See this code for an example:

public class Parent
{
    int thing = 1;
}


public class Child1 : Parent
{
    public string name;

    public Child1(string p)
    {
        this.name = p;
    }
}

public class Child2 : Parent
{
    public string name;

    public Child2(string p)
    {
        this.name = p;
    }
}

In this function we setup a Child1 object and pass it to another function.

    private void SetupStuff
    {
        Child1 x = new Child1("Bob");

        DoStuff(x);
    }

Here we can receive and "rebuild it"

    private void DoStuff(Parent obj)
    {
        Child1 rebuiltObject = ((Child1)obj);
        MessageBox.Show(rebuiltObject.name);
    }

The MessageBox will show "Bob"

Please note however that this will cause a runtime error:

    private void DoStuff(Parent obj)
    {
        Child2 rebuiltObject = ((Child2)obj);
        MessageBox.Show(rebuiltObject.name);
    }

It is smart enough to prevent you from rebuilding your object as something it never was.

jth41
  • 3,808
  • 9
  • 59
  • 109
  • This is an even worse answer than mine. It's just a runtime cast. My answer was in regard to the full previous context of the question and it's problem domain rather than a way to help him use exceptions wrong. – Magus Feb 28 '14 at 15:28
  • Though I'll certainly admit that this answers the question as it has now been edited. My only complaint is that it helps accomplish something no sane developer would do, which is the fault of the OP, not you. – Magus Feb 28 '14 at 15:46
-2

Method 1: Message Dictionaries

The best way to do this, I'd say, would be to replace both the Parent and Child classes with a simple dictionary, so you can include any number of properties as needed. This can be easily iterated over and include whatever information you need in your messages.


Method 2: Interfaces

Rather than making your Process method take a type as a parameter, I'd suggest making it generic - constrained to IParent. The call becomes:

Library.Handler.Process(ex);

Declared as:

public void Process<TMessageType>(T message) where TMessageType : IParent
{
  ScreenRecorder.Start();
  message.Print();
}

Your IParent interface would, as above, include a method called Print, which in your base parent class would print the ParentInt property you defined above, formatted as needed. Child would then look the same as it does now, with an additional override to Print.

This allows you to keep your current structure for the most part.


Method 3: Reflection

The third, worst way would be to use your current structure as is and reflect on the properties. Your DoSomething method will become a mess, and perhaps rather slow (maybe unimportant). This would require the least redesign, but at the cost of being rather terrible code.


Any of these approaches will do, but I really have to stress that the order they're presented in has a lot to do with their quality.

Magus
  • 1,302
  • 9
  • 16
  • Restructured substantially, and added more detail. Not sure it was downvote-worthy before (though admittedly it wasn't great), but it's certainly better now. – Magus Feb 26 '14 at 18:34
  • This doesn't really answer the OP's question. You just show him how to send information to another function, not how to rebuild the object. – jth41 Feb 28 '14 at 14:03
  • @jth41: My answer takes into account what he was actually asking. He's hidden details in his question recently in the hope that someone will enable him to use exceptions as messages. Because he's actually asking how to pass messages, my answer is fully accurate. Then too, it doesn't require you to know every possible child class in order to use it. – Magus Feb 28 '14 at 15:30