Calling Method of Unknown Object

  • Thread starter Thread starter Vinod I
  • Start date Start date
V

Vinod I

Hi Team,

I want to do following Task. Please let me know how should I go for it.
Thanks in advance.

I have a general method and I am getting parameters as "object" type.
No based on object type, I want to do few actions.
Like,

if(objCon.GetType() == typeof(SqlConnection))
{

objCon.Close();
}

But how I will do the "ObjCon.Close" ?......

-Vinod
 
Hi Vinod,
You will have to typecast it to the required object type. In your example,
you would

((SqlConnection) objCon).Close();

Further more, you can also get the various methods that the object supports
by using reflection if it is necessary.

Regds,

Diwakar
 
Cast the variable to the type you need (in this case, SqlConnection). That
will make the methods available.
Should be easy since you are already checking for specific types.

If you want more generic ways of doing this, you'll have to use Reflection
and call the Invoke method of the member you are looking for.

-Rob Teixeira [MVP]
 
Vinod,
You can type cast the object "objCon" as
objCon as SqlConnection, since it satisfies the "if
condition".

So u can do this
(objCon as SqlConnection).Close();

Hope this helps.

Suresh
 
Thanks Buddy. That really worked.


Diwakar Rajagopal said:
Hi Vinod,
You will have to typecast it to the required object type. In your example,
you would

((SqlConnection) objCon).Close();

Further more, you can also get the various methods that the object supports
by using reflection if it is necessary.

Regds,

Diwakar
 
Back
Top