Can a class return a value?

M

moondaddy

I'm working with c# 3.0 and am wondering if I can make a class return a
value like a function. For example, I would like to do something like this:

Point pt;
pt=SomeClass someclass=new SomeClass(double param1, double param2, double
param3);

I have some complex calculations I need to do to get a point's X and Y
values, and I wanted to break this off to a separate class. I also wanted
to make it as simple as possible to get the return value such as doing it
all in one line as above. It cant be a static class because the params
passed in will be stored as class level variables while a number of methods
process them.

Any good recommendations for this?

Thanks.
 
W

Walter Wang [MSFT]

Hi moondaddy,

This could be implemented using implicit operator
(http://msdn2.microsoft.com/en-us/library/z5z9kes2(VS.80).aspx):

class SomeClass
{
private Point m_ptResult;

public Point PtResult
{
get { return m_ptResult; }

}

public SomeClass(double p1, double p2, double p3)
{
m_ptResult = new Point(p1 + p2, p3);
}

public static implicit operator Point(SomeClass sc)
{
return sc.PtResult;
}
}



Then you could use code like this:

Point p = new SomeClass(1, 2, 3);


This feature already exists in C# 2.0.


Hope this helps.


Regards,
Walter Wang ([email protected], remove 'online.')
Microsoft Online Community Support

==================================================
When responding to posts, please "Reply to Group" via your newsreader so
that others may learn and benefit from your issue.
==================================================

This posting is provided "AS IS" with no warranties, and confers no rights.
 
G

Guest

Hi Walter,

In that case there is no point in using instance variables because no
reference to the instance is maintained and the OP might as well use a static
class.

Using your class it can be done in two lines though (I am not sure I agree
with the OP's suggestion as it does not exactly improve readability of the
code):

SomeClass c;
Point pt = (c = new SomeClass(1, 2, 3));

:) Jakob
 

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