Solved

Casting a ref variable..

Posted on 2003-11-05
2
262 Views
Last Modified: 2010-04-16
Hi,

I wanted to cast a reference to another type..
I have a class Port which implements IPortInput ..

My current variable is : IPortInput anInputPort;

And I have a method as follows: public void Test(ref Port){}

So if I want to call this method by passing a reference of anInputPort (IPortInput) as a type Port instead of type IPortInput which requires casting how can I do that?

Since casting directly by using (Port) ref anInputPort or ref (Port) anInputPort doesnt work..

Can someone give me an example please. Thanks..
0
Comment
Question by:heboh
2 Comments
 
LVL 15

Accepted Solution

by:
SRigney earned 50 total points
ID: 9692039
Why is your current variable
IPortInput anInputPort?

Don't you want to create a main variable of the specific type and the interface is only used by functions that require interface only functionality?

In any case doing something like this should work.
IPortInput anInputPort = new Port();

Port PortToSend = (Port)anInputPort;
Test(ref PortToSend);


If you want to do it within the function call you probably need another layer of parenthesis.  I didn't test this, so I'm not sure if it will work.

Test(ref ((Port) anInputPort));

Good Luck, let me know how it goes.
0
 
LVL 10

Expert Comment

by:ptmcomp
ID: 9702866
Why are you passing it as a reference?? There is usually no sense to do this. If you need to change it then return the changed value.

public Port Test(IPortInput anInputPort)
{

}
0

Featured Post

Active Directory Webinar

We all know we need to protect and secure our privileges, but where to start? Join Experts Exchange and ManageEngine on Tuesday, April 11, 2017 10:00 AM PDT to learn how to track and secure privileged users in Active Directory.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Extention Methods in C# 3.0 by Ivo Stoykov C# 3.0 offers extension methods. They allow extending existing classes without changing the class's source code or relying on inheritance. These are static methods invoked as instance method. This…
Calculating holidays and working days is a function that is often needed yet it is not one found within the Framework. This article presents one approach to building a working-day calculator for use in .NET.
The Email Laundry PDF encryption service allows companies to send confidential encrypted  emails to anybody. The PDF document can also contain attachments that are embedded in the encrypted PDF. The password is randomly generated by The Email Laundr…

830 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question