Hi Guys
NP57 Meaning of the code
I got this program from the following website. I have problem in understanding the program.
- Bill.LeftShoe = new Shoe();
- Bill.RightShoe = new Shoe();
What do the above codes mean and what is the purpose of the above code. Because without these two codes program is producing same output. Anyone knows please explain the reason.
http://www.c-sharpcorner.com/UploadFile/rmcochran/chsarp_memory401152006094206AM/chsarp_memory4.aspx
Thank you
using System;
class Program_byMaha
{
public static void
{
Shoe pgm = new Shoe();
Dude Bill = new Dude();
Bill.Name = "Bill";
//Bill.LeftShoe = new Shoe();
//Bill.RightShoe = new Shoe();
Bill.LeftShoe.Color = Bill.RightShoe.Color = "Blue";
Dude Ted = Bill.CopyDude();
Ted.Name = "Ted";
Ted.LeftShoe.Color = Ted.RightShoe.Color = "Red";
Console.WriteLine(Bill.ToString());
Console.WriteLine(Ted.ToString());
}
}
public struct Shoe
{
public string Color;
}
public class Dude
{
public string Name;
public Shoe RightShoe;
public Shoe LeftShoe;
public Dude CopyDude()
{
Dude newPerson = new Dude();
newPerson.Name = Name;
newPerson.LeftShoe = LeftShoe;
newPerson.RightShoe = RightShoe;
return newPerson;
}
public override string ToString()
{
return (Name + " : Dude!, I have a " + RightShoe.Color
+ " shoe on my right foot, and a " + LeftShoe.Color + " on my left foot.");
}
}
/*
Bill : Dude!, I have a Blue shoe on my right foot, and a Blue on my left foot.
Ted : Dude!, I have a Red shoe on my right foot, and a Red on my left foot.
*/
Posted Nov 14, 2007, 1:25 PM
Thank you very much for the help, Scott Lysle
Scott LyslePosted Nov 14, 2007, 8:26 AM
Given shoe is a struct, those two lines can be commented out and it will still run, however, if you change the declaration of shoe to represent a class instead of a struct and try to run it without the two commented out lines, the code will fail as there will be no instance of the object. If you remove the comments on those two lines and run the code again, it will run fine.
I did not look at your full example but it appears as though the intent may have been to point out that difference between the use of a struct versus a class. When declaring an instance of a class, you need to use 'new' as per your example.