Link to home
Start Free TrialLog in
Avatar of jackjohnson44
jackjohnson44

asked on

c# how do I pass a generic object to a forms constructor

For some reason, this wont' work

//wont work
        public FormXmlViewer(<T> objectToView)
//will work
        public FormXmlViewer(string objectAsStgring)
Avatar of Meir Rivkin
Meir Rivkin
Flag of Israel image

Try
Public class  FormXmlViewer<T> : Form{
public FormXmlViewer(T objectToView){
}

}
Avatar of jackjohnson44
jackjohnson44

ASKER

Thanks.

I tried what is below and my InitializeComponent is having an error.  Is this a problem if I want two constructors, one with a string and the other with a generic?


    public partial class FormXmlViewer<T> : Form
    {
        public FormXmlViewer(string xmlSource)
        {
            InitializeComponent();
        }
        public FormXmlViewer(T objectToView)
        {
            InitializeComponent();
        }
Hi

Instead of passing string as parameter, we can specify it as object and check the type before doing any function with the parameter.

public FormXmlViewer(object obj)
{
     InitializeComponent();
}
Thanks, but I don't want to specify the objects in the function.  My current form has an xml string.  I also have a deserialize function that you pass an object and get back a string.

So I can currently do:
string xmlString = GetStringFromObject(myObject)  //this uses generics and works with many objects
Form myForm(xmlString)

In this scenario I never have to know the type of object.  I want to avoid having to do this in two steps and also have to edit the form for each new object.
change this:
  public partial class FormXmlViewer<T> : Form
    {
        public FormXmlViewer(string xmlSource)
        {
            InitializeComponent();
        }
        public FormXmlViewer(T objectToView)
        {
            InitializeComponent();
        }

Open in new window


to this:

 
 public partial class FormXmlViewer<T> : Form
    {
        public FormXmlViewer(string xmlSource)
        {
            //deserialize xmlSource to T first, then call the 2nd ctor with the object.

        }
        public FormXmlViewer(T objectToView)
        {
            InitializeComponent();
        }

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Meir Rivkin
Meir Rivkin
Flag of Israel image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Thanks, I tried that.  Please see my comment above posted on 2013-05-24 at 08:25:59
look closely what i've posted, only one constructor calls InitializeComponent()
Thanks, I didn't notice that.  Can you please explain why it isn't needed?  I just thought it was always required.