Reputation: 445
I have two functions in C# that look something like this :
public static int Foo(int para1, int para2)
{
//do something
}
public static int Foo(ref int para1, ref int para2)
{
//do the same thing as overloaded function
}
This two functions is doing exactly the same thing, the only different part is that one is pass by value that it cannot alter the parameter, and another one is pass by reference and it can alter the parameter. I think of doing it like this:
public static int Foo(int para1, int para2)
{}
public static int Foo(ref int para1, ref int para2)//intend to change the value of the parameter
{
Foo(para1,para2);//will not change the value of para1, para2
}
but it won't work as it will make these two functions become the same exact functions. Or this:
public static int Foo(int para1, int para2)
{}
public static int Foo(ref int para1, ref int para2)//intend to change the value of the parameter
{
Foo(ref para1,ref para2);//keep calling itself recursively, infinite loop
}
So I have no choice but copy the exact same code from one function to another. I know that copy paste code is not a good practice in programming as it violates the DRY principle.
Do I have any other way to achieve this objective other than function overloading? Maybe something like this:
public static int Foo((optional pass by ref) para1, (val||ref) para2)
{
//do something
}
Reference: Difference between pass by value and pass by reference, out
.
Upvotes: 1
Views: 104
Reputation: 157136
I really doubt if your design is sound, I can't really judge that now.
For your current coding problem, I would switch the call:
public static int Foo(int para1, int para2)
{
return Foo(ref para1, ref para2);
}
public static int Foo(ref int para1, ref int para2)
{
//do something
}
This way, only the local copy in the first method is changed, not the values passed in to the method. 'Foo with ref' still works the same.
Upvotes: 1