get method

  • Thread starter Thread starter juli jul
  • Start date Start date
J

juli jul

Hello I want to write get method of some object I create in other class:
I am doing some like that:

public ABC
{
get
{
return ABC;
}


}

or I should define a private member and than do something like:

private abc=new abc() and than return it ?

Thank you!
 
First, to clarify: When you say you want to write a get method to
return some object you create "in another class," I assume that you
meant "in the class that declares the get method," right? Or do you
mean that you want to write a get method in class A to return an object
that gets created in class B?

Assuming it's the former: that class A creates the object and then
returns it via a get method in that same class A, then the two options
you outlined are used in different scenarios.

The code you wrote, something like:

public ClassB ABC { get { return this._abc; }}

where "_abc" is a private member of the class, would be used if the
object is created earlier, in response to something else the caller
does, and then you just return identically the same object every time
the caller says "myClassA.ABC". This happens often, such as when the
object _abc is created when an instance of the class is constructed:

public class ClassA
{
private ClassB _abc;

public ClassA(...)
{
this._abc = new ClassB(...)
}

public ClassB ABC { get { return this._abc; }}
}

Another possibility is that you want to construct new a "ClassB" every
time the caller invokes "ABC", and return a different object each time.
In that case, you would say

public ClassA
{
...
public ClassB ABC { get { return new ClassB(...); }}
}

There are other scenarios as well, in which the caller has to call some
other method before invoking ABC, and that other method constructs the
_abc object, but these are less common.
 
Juli,

Well, you would have to. The compiler will give you an error when you
try and return just the type name. You need to pass it an instance of
something.

Hope this helps.
 

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

Back
Top