Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What to pass? Reference Object or Value Type?

Tags:

c#

oop

Guys I have a "best practice question" For example I have this classes:

class Person
{
   public int age {get; set;}
}

class Computer
{
   public void checkAge(Person p)  // Which one is recommended   THIS
   {
       // Do smthg with the AGE
   }

   public void checkAge(int p)     // OR THIS
   {
       //Do smthg with the age.
   }
}

What is recommended to pass? Just what I need (int-value type) or the whole object (reference type)

Im asking this because Im using LINQ on an app that I am making and I have created many entities where I should pass the IDs (foreing keys), but Im passing objects.

What is the best approach?

like image 324
MRFerocius Avatar asked Feb 15 '10 18:02

MRFerocius


People also ask

Is it better to pass by reference or value?

Pass-by-references is more efficient than pass-by-value, because it does not copy the arguments. The formal parameter is an alias for the argument. When the called function read or write the formal parameter, it is actually read or write the argument itself.

Why is it usually better to pass objects by reference than by value?

The reason is simple: if you passed by value, a copy of the object had to be made and, except for very small objects, this is always more expensive than passing a reference.

Is object reference type or value type?

An object variable is always a reference-type. Classes and string are reference type. Struct and enum are kind of value types.

Can you pass an object by reference?

Pass by reference means that you have to pass the function(reference) to a variable which refers that the variable already exists in memory. Here, the variable( the bucket) is passed into the function directly. The variable acts as a Package that comes with its contents(the objects).


2 Answers

The function checkAge should only take in the minimum amount of information needed to perform it's job. Adding anything else just creates an artificial dependency. If only an int is needed then that is the solution I should take.

like image 146
JaredPar Avatar answered Sep 20 '22 12:09

JaredPar


I would argue that in this case, the answer is probably neither. Either "Age" would be factored out into its own class, or if the operation is context-specific with Person, it would be found inside the Person class itself.

like image 36
Dave Markle Avatar answered Sep 20 '22 12:09

Dave Markle