473,385 Members | 1,824 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,385 software developers and data experts.

Question on operator 'new' in c#.

I found in internet this example of code. I'd like to know somthing about
what happens behind the scenes when these lines of code are executed:

//----------- Code Snippet ----------------------------

GenericCustomer[] Customers = new GenericCustomer[2];

Customers[0] = a;

Customers[1] = b;

//------------End Of Code Snippet-------------------------------------------

If i would be in a C/C++ environment this should be a dangling reference,
but since i've a garbage collector, what happen to the two objects created
with "new[2]", are they replaced by the two objects or are they passed to
the Garbage Collector to determine they life-time...?

//--------------------------------------Complete
Example---------------------------

public abstract class GenericCustomer {

private string name;

protected decimal balance;

public override string toString() {

string Result = "Customer: "+name;

Result+= ", owing: "+balance;

return Result;

}
public string Name {

get {

return name;

}

set {

name = value;

}

}
public decimal Balance {

get {

return balance;

}

}
public void RecordPayment(decimal amountPaid) {

balance += amountPaid;

}
public abstract void RecordCal(uint nMinutes)

}

public class PayAsYouGoCustomer : GenericCustomer {

public override void RecordCall(uint nMinutes) {

balance += nMinutes*0.5;

}

}

public class GoldCustomer : GenericCustomer {

public override void RecordCall(uint nMinutes) {

balance += nMinutes*0.1;

}

}

public class EntryPoint {

public static void Main() {

GenericCustomer a = new GoldCustomer();
GenericCustomer b = new PayAsYouGoCustomer();

a.name = "A";
b.name = "B";

GenericCustomer[] Customers = new GenericCustomer[2];

Customers[0] = a;
Customers[0].RecordCall(25);
Customers[0].RecordCall(75);
Customers[1] = b;
Customers[1].RecordCall(75);

foreach (GenericCustomer customer in Customers) {

Console.WriteLine("{0} owes {1}", customer.Name, customer.Balance);

}
}

}

//--------------------------------------End of Complete
Example---------------------------

Nov 15 '05 #1
8 1007
The new[2] does not create 2 GenericCustomer objects. This is a big
difference between c/c++ and c#. The new does nothing more than create the
array. The contents of the array are empty.

In c#, if you want to create an array and fill it with object (like what
c/c++ does), you need to assign each element in the array to a new
GenericCustomer.

I hope I understood your question and that this helps,
Kevin

"Andrea" <ky*****@hotmail.com> wrote in message
news:eU**************@TK2MSFTNGP11.phx.gbl...
I found in internet this example of code. I'd like to know somthing about
what happens behind the scenes when these lines of code are executed:

//----------- Code Snippet ----------------------------

GenericCustomer[] Customers = new GenericCustomer[2];

Customers[0] = a;

Customers[1] = b;

//------------End Of Code

Snippet-------------------------------------------
Nov 15 '05 #2
Hi Andrea,

Your basically right. The two GenericCustomer objects created in the first
line will no longer have references to them after the third line completes
and thus they will be destroyed the next time the garbage collector runs. It
should be noted that unless you explicitly request a garbage collection
there is no way to know when the next collection will occur, it may not
happen until just before the application terminates.

--
Rob Windsor
G6 Consulting
Toronto, Canada
"Andrea" <ky*****@hotmail.com> wrote in message
news:eU**************@TK2MSFTNGP11.phx.gbl...
I found in internet this example of code. I'd like to know somthing about
what happens behind the scenes when these lines of code are executed:

//----------- Code Snippet ----------------------------

GenericCustomer[] Customers = new GenericCustomer[2];

Customers[0] = a;

Customers[1] = b;

//------------End Of Code Snippet-------------------------------------------
If i would be in a C/C++ environment this should be a dangling reference,
but since i've a garbage collector, what happen to the two objects created
with "new[2]", are they replaced by the two objects or are they passed to
the Garbage Collector to determine they life-time...?

//--------------------------------------Complete
Example---------------------------

public abstract class GenericCustomer {

private string name;

protected decimal balance;

public override string toString() {

string Result = "Customer: "+name;

Result+= ", owing: "+balance;

return Result;

}
public string Name {

get {

return name;

}

set {

name = value;

}

}
public decimal Balance {

get {

return balance;

}

}
public void RecordPayment(decimal amountPaid) {

balance += amountPaid;

}
public abstract void RecordCal(uint nMinutes)

}

public class PayAsYouGoCustomer : GenericCustomer {

public override void RecordCall(uint nMinutes) {

balance += nMinutes*0.5;

}

}

public class GoldCustomer : GenericCustomer {

public override void RecordCall(uint nMinutes) {

balance += nMinutes*0.1;

}

}

public class EntryPoint {

public static void Main() {

GenericCustomer a = new GoldCustomer();
GenericCustomer b = new PayAsYouGoCustomer();

a.name = "A";
b.name = "B";

GenericCustomer[] Customers = new GenericCustomer[2];

Customers[0] = a;
Customers[0].RecordCall(25);
Customers[0].RecordCall(75);
Customers[1] = b;
Customers[1].RecordCall(75);

foreach (GenericCustomer customer in Customers) {

Console.WriteLine("{0} owes {1}", customer.Name, customer.Balance);

}
}

}

//--------------------------------------End of Complete
Example---------------------------


Nov 15 '05 #3
Thus spake Andrea:
GenericCustomer[] Customers = new GenericCustomer[2]; <snip> If i would be in a C/C++ environment this should be a dangling
reference, but since i've a garbage collector, what happen to the two
objects created with "new[2]", are they replaced by the two objects
or are they passed to the Garbage Collector to determine they
life-time...?


A simple test will reveal that you have an array of null references.

--
There are 10 kinds of people. Those who understand binary and those who
don't.

http://code.acadx.com
Nov 15 '05 #4
100

"Rob Windsor" <rw******@NO.MORE.SPAM.bigfoot.com> wrote in message
news:e3**************@TK2MSFTNGP11.phx.gbl...
Hi Andrea,

Your basically right. The two GenericCustomer objects created in the first
line will no longer have references to them after the third line completes
and thus they will be destroyed the next time the garbage collector runs. It should be noted that unless you explicitly request a garbage collection
there is no way to know when the next collection will occur, it may not
happen until just before the application terminates.

--
Rob Windsor
G6 Consulting
Toronto, Canada
Hi Rob,
Speaking of C# the first line creates only one object and it is of type
derived from System.Array. There is no GenericCustomer objects created. To
be more strict GenericCustomer objects will be created if GenericCustomer is
a vaue type. In the last case these value-type objects are not considered
for GC, though.

This is the big difference between C/C++ and C# arrays.

B\rgds
100


"Andrea" <ky*****@hotmail.com> wrote in message
news:eU**************@TK2MSFTNGP11.phx.gbl...
I found in internet this example of code. I'd like to know somthing about what happens behind the scenes when these lines of code are executed:

//----------- Code Snippet ----------------------------

GenericCustomer[] Customers = new GenericCustomer[2];

Customers[0] = a;

Customers[1] = b;

//------------End Of Code

Snippet-------------------------------------------

If i would be in a C/C++ environment this should be a dangling reference, but since i've a garbage collector, what happen to the two objects created with "new[2]", are they replaced by the two objects or are they passed to the Garbage Collector to determine they life-time...?

//--------------------------------------Complete
Example---------------------------

public abstract class GenericCustomer {

private string name;

protected decimal balance;

public override string toString() {

string Result = "Customer: "+name;

Result+= ", owing: "+balance;

return Result;

}
public string Name {

get {

return name;

}

set {

name = value;

}

}
public decimal Balance {

get {

return balance;

}

}
public void RecordPayment(decimal amountPaid) {

balance += amountPaid;

}
public abstract void RecordCal(uint nMinutes)

}

public class PayAsYouGoCustomer : GenericCustomer {

public override void RecordCall(uint nMinutes) {

balance += nMinutes*0.5;

}

}

public class GoldCustomer : GenericCustomer {

public override void RecordCall(uint nMinutes) {

balance += nMinutes*0.1;

}

}

public class EntryPoint {

public static void Main() {

GenericCustomer a = new GoldCustomer();
GenericCustomer b = new PayAsYouGoCustomer();

a.name = "A";
b.name = "B";

GenericCustomer[] Customers = new GenericCustomer[2];

Customers[0] = a;
Customers[0].RecordCall(25);
Customers[0].RecordCall(75);
Customers[1] = b;
Customers[1].RecordCall(75);

foreach (GenericCustomer customer in Customers) {

Console.WriteLine("{0} owes {1}", customer.Name, customer.Balance);

}
}

}

//--------------------------------------End of Complete
Example---------------------------



Nov 15 '05 #5
thank you all.
How do you do this memory test?
"Frank Oquendo" <fr****@acadx.com> ha scritto nel messaggio
news:uw**************@tk2msftngp13.phx.gbl...
Thus spake Andrea:
GenericCustomer[] Customers = new GenericCustomer[2];

<snip>
If i would be in a C/C++ environment this should be a dangling
reference, but since i've a garbage collector, what happen to the two
objects created with "new[2]", are they replaced by the two objects
or are they passed to the Garbage Collector to determine they
life-time...?


A simple test will reveal that you have an array of null references.

--
There are 10 kinds of people. Those who understand binary and those who
don't.

http://code.acadx.com

Nov 15 '05 #6
Thus spake Andrea:
thank you all.
How do you do this memory test?


Here's some code. Substitute your GenericCustomer class to make the test
more relevant to your scenario:

using System;

namespace ConsoleApplication3
{
class Class1
{
[STAThread]
static void Main(string[] args)
{
object[] objects = new object[2];
string temp;

for (int i = 0; i < objects.Length; i++)
{
temp = objects[i] == null ? "null" : "instantiated";
Console.WriteLine("Object {0} is {1}", i, temp);
}

Console.ReadLine();
}
}
}

--
There are 10 kinds of people. Those who understand binary and those who
don't.

http://code.acadx.com
Nov 15 '05 #7
thanks again.

"Frank Oquendo" <fr****@acadx.com> ha scritto nel messaggio
news:%2****************@TK2MSFTNGP09.phx.gbl...
Thus spake Andrea:
thank you all.
How do you do this memory test?


Here's some code. Substitute your GenericCustomer class to make the test
more relevant to your scenario:

using System;

namespace ConsoleApplication3
{
class Class1
{
[STAThread]
static void Main(string[] args)
{
object[] objects = new object[2];
string temp;

for (int i = 0; i < objects.Length; i++)
{
temp = objects[i] == null ? "null" : "instantiated";
Console.WriteLine("Object {0} is {1}", i, temp);
}

Console.ReadLine();
}
}
}

--
There are 10 kinds of people. Those who understand binary and those who
don't.

http://code.acadx.com

Nov 15 '05 #8
Andrea <ky*****@hotmail.com> wrote:
How do you do this memory test?


if (Customers[0]==null)
...

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

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

Similar topics

11
by: billnospam | last post by:
Is it possible to overload operators in vb.net? Is it possible to do programmer defined boxing on byvalue variables in vb.net?
5
by: bsaucer | last post by:
I am creating a class with operator overloads. It makes references to another class I've created, but do not wish to modify. I try to overload an operator having arguments having the other class...
33
by: Mohanasundaram | last post by:
Hi All, As per the standard what is the result of passing NULL to both malloc and free? Regards, Mohan. http://www.gotw.ca/resources/clcm.htm for info about ]
20
by: Ioannis Vranos | last post by:
When we use the standard placement new operator provided in <new>, and not a definition of owr own, isn't a call to placement delete enough? Consider the code: #include <new>
2
by: grahamo | last post by:
Hi, I realise that c++ knows nothing about threads however my question is related to an (excellent) article I was reading about threads and C++. For all intents and purposes we can forget the...
5
by: Tony Johansson | last post by:
Hello experts! I have two class template below with names Array and CheckedArray. The class template CheckedArray is derived from the class template Array which is the base class This program...
7
by: Eckhard Lehmann | last post by:
Hi, I try to recall some C++ currently. Therefore I read the "Standard C++ Bible" by C. Walnum, A. Stevens and - of course there are chapters about operator overloading. Now I have a class...
17
by: ma740988 | last post by:
Consider: # include <iostream> # include <algorithm> # include <vector> # include <string> using namespace std; class msg { std::string someStr;
7
by: Stephan Rose | last post by:
I am currently working on an EDA app and heavily working on squeezing the last bits of performance out of it. Going as far as sending batches of geometry to the video card while still processing...
2
by: sven.bauer | last post by:
Hi, I have a question following up the following slightly older posting: http://groups.google.de/group/comp.lang.c++/browse_thread/thread/40e52371e89806ae/52a3a6551f84d38b class Base {...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
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: 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?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...

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.