Pass Class as parameter in a method.

D

Dion Heskett

How can I pass a Class as a parameter to in a method ?

i.e.

Private myMethod( string pram1, Classobject as pram2)
{

Classobject.DataSource = reader;
Classobject.DataBind();
}

I wish to pass either a System.Web.UI.WebControls.DataGrid or
System.Web.UI.WebControls.Repeater class object.

Is this possible ?

Many Thanks

Dion
 
I

Ignacio Machin

Hi Dion,

You do not pass a class, you pass an instance of a class , the method would
look like :

void myMethod( string param1, DataGrid param2)
{

}

Now, even as a DataGrid and a Repeater both have a DataSource property its
parent class ( System.Web.UI.Control ) does not provide it, therefore if you
use the same function and pass an instance of a DataGrid and/or Repeater,
you should declare the second parameter as Control and then later in the
method test the type of the parameter ( you can use the "is" operator ) :
if ( param2 is System.Web.UI.DataGrid )
{
DataGrid grid = (DataGrid) param2;
grid.DataSource = ....
}
else

if ( param2 is System.Web.UI.Repeater )
{
Repeater grid = (Repeater ) param2;
grid.DataSource = ....
}

As you can see you will have to write the same code twice anyway. Now that I
think on it you could use reflection and write the code once, something like
this:
if ( param2 is System.Web.UI.Repeater || param2 is
System.Web.UI.DataGrid )
{
//using reflection assign to the property the value
}


Or you can write two methods with the second parameter beign the exact type.


Hope this help,
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top