473,387 Members | 1,582 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

Constant parameters

Hi,

I have a method which receives an argument of which I need to change some
values before I use it. But I don't want to alter the object for the caller.
How do I achieve this? Do I need to make a local copy of the obect in my
method, or otherwise "manually" ensure that the object remains unaltered
when my method exits?

For example, see the method below. Here, the caller supplies "anArgument",
which my method alters, but I don't want the caller to see this change -
that is, I want the caller's object to remain unaltered when my method
exits.

public IResult DoSomeStuff( IArg anArgument )
{
IResult result = new MyResult();
anArgument.Value = anArgument.Value + 1;
return result;
}

Thanks,
Peter
Nov 17 '05 #1
5 1658
C# always takes objects by reference only. Suppose the passed parameter
should not be altered then it can be declared as readonly field.

Some thing like this..

public class Class1
{
public readonly string teststring;

Class1(string testmessage)
{
this.teststring = testmessage
}
}
void TestMethod(string arg)
{
arg += "is an Message"
}

Class1 tempclass1 = new Class1("Message");
Testmethod(tempclass1.teststring);

Though the arg is changed, the value of tempclass1.teststring remains
unaltered.

Regards
Prakash Prabhu K

"Peter Kirk" wrote:
Hi,

I have a method which receives an argument of which I need to change some
values before I use it. But I don't want to alter the object for the caller.
How do I achieve this? Do I need to make a local copy of the obect in my
method, or otherwise "manually" ensure that the object remains unaltered
when my method exits?

For example, see the method below. Here, the caller supplies "anArgument",
which my method alters, but I don't want the caller to see this change -
that is, I want the caller's object to remain unaltered when my method
exits.

public IResult DoSomeStuff( IArg anArgument )
{
IResult result = new MyResult();
anArgument.Value = anArgument.Value + 1;
return result;
}

Thanks,
Peter

Nov 17 '05 #2
"Peter Kirk" <pk@alpha-solutions.dk> wrote in message
news:uM**************@TK2MSFTNGP10.phx.gbl...
Hi,

I have a method which receives an argument of which I need to change some
values before I use it. But I don't want to alter the object for the
caller. How do I achieve this? Do I need to make a local copy of the obect
in my method, or otherwise "manually" ensure that the object remains
unaltered when my method exits?

For example, see the method below. Here, the caller supplies "anArgument",
which my method alters, but I don't want the caller to see this change -
that is, I want the caller's object to remain unaltered when my method
exits.

public IResult DoSomeStuff( IArg anArgument )
{
IResult result = new MyResult();
anArgument.Value = anArgument.Value + 1;
return result;
}

Thanks,
Peter


Hi Peter.

A class should be self-contained. Hence a method of some class should not
try to copy an object; the object should know how to copy itself. The
pattern is called Cloning.

In .NET there is a interface called IClonable which is useless in .NET 1.1
(as it force you to return Object) but will be powerful in 2.0 with generics
(as it may return type of itself).

I would suggest you add the method .Clone() to your class but without
implementing IClonable.

Simple example:

public class Person
{
string name;
int age;

public Person Clone()
{
Person p = new Person();
p.name = this.name;
p.age = this.age;
return p;
}
}

Happy Coding
- Michael S

Nov 17 '05 #3

"Michael S" <a@b.c> skrev i en meddelelse
news:On**************@TK2MSFTNGP09.phx.gbl...
"Peter Kirk" <pk@alpha-solutions.dk> wrote in message
news:uM**************@TK2MSFTNGP10.phx.gbl...
public IResult DoSomeStuff( IArg anArgument )
{
IResult result = new MyResult();
anArgument.Value = anArgument.Value + 1;
return result;
}

Thanks,
Peter


Hi Peter.

A class should be self-contained. Hence a method of some class should not
try to copy an object; the object should know how to copy itself. The
pattern is called Cloning.

In .NET there is a interface called IClonable which is useless in .NET 1.1
(as it force you to return Object) but will be powerful in 2.0 with
generics (as it may return type of itself).

I would suggest you add the method .Clone() to your class but without
implementing IClonable.

Simple example:

public class Person
{
string name;
int age;

public Person Clone()
{
Person p = new Person();
p.name = this.name;
p.age = this.age;
return p;
}
}


OK, thanks for the answer. I had done it like:

public class Person
{
string name;
int age;

public Person(string name, int age)
{
this.name = name;
this.age = age;
}

public Person(Person p)
{
this.name = p.name;
this.age = p.age;
}

...methods for person etc...
}

Where I have a constructor which copies a supplied Person. Are there
disadvantages to this approach over the Clone approach you suggest? In my
method where I use a person, I do this:

public IResult DoSomeStuff( Person person )
{
IResult result = new MyResult();

Person localPerson = new Person(person);

// now I work with "localPerson", not "person" ...

return result;
}
But basically, I do myself need to code the functionality of maintaining the
state of the argument object.

Thanks,
Peter

Nov 17 '05 #4
This is really interesting Peter.

In Java, the recent fad is to make everything immutable. Hence there are no
getters and setters but every object is set by the constructor and then
creating new objects via the constructor is your only option when you wanna
change values. If you ask me this is a loose-loose way of doing things.

In .NET we tend to have mutable objects. Hence a object will (most often) be
instanced with defualt values and we use properties to get/set values.
Overloaded constructors are considered shortcuts or binders.

I like the cloning approach, as it shows very clearly that you are indeed
making a copy of the object.
But I'm not sure I like the overloaded constructor with a default
constructor. I think it should be either way.

1. Just a default constructor. Consumer should set properties. (.NET-style)
2. A overloaded constructor. Default constructor is private. (Java-style)

Anyways, I think using a Clone method is better than having a overloaded
constructor:

Person anotherPerson = firstPerson.Clone(); // I like this. For me it
clearly says i will have a copy.
Person anotherPerson = new Person(firstPerson); //I don't like this. Will I
get a copy? Will they marry or does anotherPerson just hump the first one?
What is the state of firstPerson after being humped? Must I check if either
one or both have a wedding-ring? =)

In the .NET framework we have stuff like myCommand = new
SqlCommand("sql...", myConnection) that clearly join a command to a
connection. This is why I don't like the having constructors for cloning as
it implies inter-references rather than copying in .NET.

And never forget the last words of Mahatma Gandhi:
- When your coding C# in a mutual world, don't try to pretend it's immutal.
That's bad for karma!

Happy Coding
- Michael S



"Peter Kirk" <pk@alpha-solutions.dk> wrote in message
news:uk**************@tk2msftngp13.phx.gbl...

"Michael S" <a@b.c> skrev i en meddelelse
news:On**************@TK2MSFTNGP09.phx.gbl...
"Peter Kirk" <pk@alpha-solutions.dk> wrote in message
news:uM**************@TK2MSFTNGP10.phx.gbl...
public IResult DoSomeStuff( IArg anArgument )
{
IResult result = new MyResult();
anArgument.Value = anArgument.Value + 1;
return result;
}

Thanks,
Peter


Hi Peter.

A class should be self-contained. Hence a method of some class should not
try to copy an object; the object should know how to copy itself. The
pattern is called Cloning.

In .NET there is a interface called IClonable which is useless in .NET
1.1 (as it force you to return Object) but will be powerful in 2.0 with
generics (as it may return type of itself).

I would suggest you add the method .Clone() to your class but without
implementing IClonable.

Simple example:

public class Person
{
string name;
int age;

public Person Clone()
{
Person p = new Person();
p.name = this.name;
p.age = this.age;
return p;
}
}


OK, thanks for the answer. I had done it like:

public class Person
{
string name;
int age;

public Person(string name, int age)
{
this.name = name;
this.age = age;
}

public Person(Person p)
{
this.name = p.name;
this.age = p.age;
}

...methods for person etc...
}

Where I have a constructor which copies a supplied Person. Are there
disadvantages to this approach over the Clone approach you suggest? In my
method where I use a person, I do this:

public IResult DoSomeStuff( Person person )
{
IResult result = new MyResult();

Person localPerson = new Person(person);

// now I work with "localPerson", not "person" ...

return result;
}
But basically, I do myself need to code the functionality of maintaining
the state of the argument object.

Thanks,
Peter

Nov 17 '05 #5
Prakash Prabhu K <Pr************@discussions.microsoft.com> wrote:
C# always takes objects by reference only.


No. This is a very, very dangerous thing to say, as it's technically
inaccurate and will mislead people who truly understand "by reference"
semantics. (I've seen it happen lots of times.)

See http://www.pobox.com/~skeet/csharp/parameters.html for the truth of
the matter.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 17 '05 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
by: Piotr Bartczak | last post by:
I've started learning C# (after C++) and I found that there is no way to make an object constant. In C++ there is a const modifier which allows me to define an object which will not change after...
1
by: Craig Stadler | last post by:
mySQL (4.0.20a win32), dual amd2200 machine, 4 gigs of DDR ECC memory. I have a series of 33 tables, identical in structure : (field names shortened) CREATE TABLE `dbtable1` ( `FS`...
4
by: Günter Zöchbauer | last post by:
can anyone tell why is valid but produces compiler error: An attribute argument must be a constant expression, typeof expression or array creation expression
11
by: lovecreatesbeauty | last post by:
Hello experts, Is const_cast only applied to pointers or references? If I have a constant object, then how can I remove constant attribute from it? #include <vector> #include <string>...
6
by: fctk | last post by:
hello, i'm trying to compile this small program: int main(void) { unsigned long int max; max = 4000000000;
13
by: hn.ft.pris | last post by:
Hi: I have the following simple program: #include<iostream> using namespace std; int main(int argc, char* argv){ const double L = 1.234; const int T = static_cast<const int>(L); int arr;
13
by: Szabolcs | last post by:
Is the following legal? void fun(int N) { int arr; } gcc and Digital Mars accept it, but msvc complains that it wants a constant expression.
1
by: Jeremy | last post by:
Looks like c# does not have the ability to create constant methods or constant parameters, is there an equilavent, or a reason why it was taken out?
4
by: Gordon | last post by:
I'm trying to get a constant from a class, where the constant's name is known, but the class name isn't. I want to do things this way because I want classes to be able to define certain aspects...
8
by: Stefano Sabatini | last post by:
Hi all, I'm encountering this while trying to implement a factory singleton method to generate objects. The singleton has a static map which binds a static creation function defined in each...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.