Question

I'm in need of clarification with regards the way in which a object can be return from a method in C#. I have the following class;

public class Person
{
    public string Forename {get;set;}
    public string Surname {get;set;}
}

My generic function is;

public static Person MyFunction()
{
    Person oPerson = new Person();
    oPerson.Forename = "Joe";
    oPerson.Surname = "King";
    return oPerson;
}

Is there any different between the following two calls

Person oPerson = new Person();
oPerson = MyFunction();

and

Person oPerson = MyFunction();

Is it correct to call the new operator like

Person oPerson = new Person();

even though the generic function is creating a new instance of this object and returning it.

Was it helpful?

Solution

Firstly, no your calls are not the same.

Person oPerson = new Person(); // This object is about to be discarded by...
oPerson = MyFunction(); // ... Overwriting the reference to it here

At this point the first Person you created can be cleaned up by the garbage collector.

If you have default initialization you ought to do that in a constructor for Person.

OTHER TIPS

No, the result object in oPerson should be exactly the same. The only difference I can see is, that

Person oPerson = new Person();
oPerson = MyFunction();

needs more time to execute because you are creating the object twice.

However, I don't see how your function

public static Person MyFunction()
{
    Person oPerson = new Person();
    oPerson.Forename = "Joe";
    oPerson.Surname = "King";
    return oPerson;
}

is generic as it only handles one type. Generic function look like this:

public static <T> SomeGenericFunction(T person) where T : Person
{
    person.Forename = "Joe";
    person.Surname = "King";
    return person;

}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top