Embed one struct within another

  • (2 Pages)
  • +
  • 1
  • 2

28 Replies - 1448 Views - Last Post: 06 July 2013 - 12:14 PM Rate Topic: -----

#1 Semus  Icon User is offline

  • D.I.C Head

Reputation: 14
  • View blog
  • Posts: 126
  • Joined: 27-May 13

Embed one struct within another

Posted 28 June 2013 - 09:38 AM

Following a challenge from a book I am reading (beginning to see a pattern here? :bigsmile:/>/> ) I have been asked to create a struct to store a persons first name, last name and phone number. I am supposed to embed one struct within another. Then I am supposed to populate the fields with data and display the result.

I know exactly how to do this challenge, so that's not really an issue. What I don't understand is what they mean by embedding one struct within another. Do they mean put one struct inside the other? Here's my current code:

        [il]struct[/il] Name
        {
            public string firstName;
            public string lastName;
        }
        struct Number
        {
            public string phoneNumber;
        }
        static void Main(string[] args)
        {
        }

Are they asking me to do it like this?
        struct Name
        {
            public string firstName;
            public string lastName;
            struct Number
            {
               public string phoneNumber;
            }
        }
        static void Main(string[] args)
        {
        }


This seems kind of odd to me, but is this what they mean by embedding one struct within another? I am asking because I have never seen it done this way before and it doesn't seem to work like that.

This post has been edited by Semus: 28 June 2013 - 09:53 AM


Is This A Good Question/Topic? 0
  • +

Replies To: Embed one struct within another

#2 Semus  Icon User is offline

  • D.I.C Head

Reputation: 14
  • View blog
  • Posts: 126
  • Joined: 27-May 13

Re: Embed one struct within another

Posted 28 June 2013 - 10:01 AM

I managed to fix it with a little bit of experimenting. Here's my full coding:

        struct Name
        {
            public string firstName;
            public string lastName;
            public struct Number
            {
               public string phone;
            }
        }
        static void Main(string[] args)
        {
            Name First;
            Name Last;
            Name.Number Num;
            Console.Write("Please enter your first name: ");
            First.firstName = Console.ReadLine();
            Console.Clear();
            Console.Write("Please enter your last name: ");
            Last.lastName = Console.ReadLine();
            Console.Clear();
            Console.Write("Please enter your phone number:");
            Num.phone = Console.ReadLine();
            Console.Clear();
            Console.WriteLine("Your first name is {0}", First.firstName);
            Console.WriteLine("\nYour last name is {0}", Last.lastName);
            Console.WriteLine("\nYour phone number is {0}", Num.phone);
            Console.ReadLine();
        }

Was This Post Helpful? 0
  • +
  • -

#3 Curtis Rutland  Icon User is offline

  • (╯□)╯︵ (~ .o.)~
  • member icon


Reputation: 5101
  • View blog
  • Posts: 9,283
  • Joined: 08-June 10

Re: Embed one struct within another

Posted 28 June 2013 - 11:11 AM

That's not really doing what you think its doing.

Quote

is this what they mean by embedding one struct within another?


I think they probably meant something more like this:

struct Name
{
    public string firstName;
    public string lastName;
}

struct Person
{
    public Name name;
    public string phoneNumber;
}

static void Main()
{
    Person p = new Person();
    p.name = new Name();
    p.name.firstName = "Curtis";
    p.name.lastName = "Rutland";
    p.phoneNumber = "1234567890";
}



using one struct in another, rather than defining one inside the other.

Both are legal, but what you did was place the struct's definition inside another struct. That doesn't mean that your struct Name has a number in it; it means that you've put the blueprints for the struct in there.

Also, I'd skip most of the chapters on structs. They're not overly important; in most cases you're going to use a class.
Was This Post Helpful? 0
  • +
  • -

#4 Semus  Icon User is offline

  • D.I.C Head

Reputation: 14
  • View blog
  • Posts: 126
  • Joined: 27-May 13

Re: Embed one struct within another

Posted 28 June 2013 - 11:19 AM

Yes, the struct and enum sections were rather small in the book. I am currently reading the chapter on classes and they are similar to structs but are much more useful.
Was This Post Helpful? 0
  • +
  • -

#5 Curtis Rutland  Icon User is offline

  • (╯□)╯︵ (~ .o.)~
  • member icon


Reputation: 5101
  • View blog
  • Posts: 9,283
  • Joined: 08-June 10

Re: Embed one struct within another

Posted 28 June 2013 - 11:22 AM

Classes will generally be what you use. Structs differ in where the data in them is actually stored, how they're passed to methods, and what values they can actually be (they're not nullable). It's important to know, because a lot of the built-in types in .NET are actually structs (DateTime is an example of a built-in type that is a struct), but you'll rarely want to make your own. If you don't know when to use a struct, just always use a class. When you're advanced enough to know when you need a struct, you'll be advanced enough to know how to define them.
Was This Post Helpful? 0
  • +
  • -

#6 Semus  Icon User is offline

  • D.I.C Head

Reputation: 14
  • View blog
  • Posts: 126
  • Joined: 27-May 13

Re: Embed one struct within another

Posted 28 June 2013 - 12:55 PM

I thought that I would put this here instead of making another thread. Also, I should clarify that this is different than what the thread was about. This particular post is about creating a class and using it in a program.

I want to make sure I have grasped the concept here and I am having doubts as to whether or not I did this correctly. I have a feeling I did something terribly wrong :wacko:/>

OK, so this particular challenge has asked me to create an employee class with fields for their name, address, year of birth and their hourly pay rate. The challenge did not ask me to show the data after everything was entered in, so I added a method that will display all of the employee data that was entered by the user. I hope I did this correctly. I, at the very least, hope that I am close.

Here is the main program:

namespace NewEmployeeProject
{
    class Program
    {
        static void Main(string[] args)
        {
            Employee Emp1 = new Employee();

            Console.Write("Please enter employee name: ");
            Emp1.name = Console.ReadLine();
            Console.Clear();
            Console.Write("Please enter employee address: ");
            Emp1.address = Console.ReadLine();
            Console.Clear();
            Console.Write("Please enter employee year of birth: ");
            Emp1.yearOfBirth = int.Parse(Console.ReadLine());
            Console.Clear();
            Console.Write("Please enter employee hourly pay rate: ");
            Emp1.hourlyPayRate = float.Parse(Console.ReadLine());
            Console.Clear();

            Emp1.ShowEmpInfo();

            Console.ReadLine();
        }
    }
}


And here is the class and method to show the info on the screen:

namespace NewEmployeeProject
{
    class Employee
    {
        public string name;
        public string address;
        public int yearOfBirth;
        public float hourlyPayRate;
        public void ShowEmpInfo()
        {
            Console.WriteLine("The employee's name is {0}\n", name);
            Console.WriteLine("The employee's address is {0}\n", address);
            Console.WriteLine("The employee's year of birth is {0}\n", yearOfBirth);
            Console.WriteLine("The employee's hourly pay rate is {0}\n", hourlyPayRate);
        }
    }
}


The program functions properly and things happen exactly as I expected them to. I just wanted to make sure that I was on the right track.

This post has been edited by Semus: 28 June 2013 - 12:59 PM

Was This Post Helpful? 0
  • +
  • -

#7 Curtis Rutland  Icon User is offline

  • (╯□)╯︵ (~ .o.)~
  • member icon


Reputation: 5101
  • View blog
  • Posts: 9,283
  • Joined: 08-June 10

Re: Embed one struct within another

Posted 28 June 2013 - 01:56 PM

That's a great start. Next, I suggest trying to make a method that takes values and applies them to the employee, rather than directly accessing the fields. Here's how you'd call it (look at the last line):

namespace NewEmployeeProject
{
    class Program
    {
        static void Main(string[] args)
        {
            Employee Emp1 = new Employee();

            Console.Write("Please enter employee name: ");
            string name = Console.ReadLine();
            Console.Clear();
            Console.Write("Please enter employee address: ");
            string address = Console.ReadLine();
            Console.Clear();
            Console.Write("Please enter employee year of birth: ");
            int yearOfBirth = int.Parse(Console.ReadLine());
            Console.Clear();
            Console.Write("Please enter employee hourly pay rate: ");
            float hourlyPayRate = float.Parse(Console.ReadLine());
            Console.Clear();

            Emp1.SetValues(name, address, yearOfBirth, hourlyPayRate);
        }
    }
}



I leave it as a challenge to you to write the method itself.
Was This Post Helpful? 1
  • +
  • -

#8 Semus  Icon User is offline

  • D.I.C Head

Reputation: 14
  • View blog
  • Posts: 126
  • Joined: 27-May 13

Re: Embed one struct within another

Posted 28 June 2013 - 02:36 PM

I'm not sure I understand, Curtis. isn't the Main method doing exactly that? It's taking values that I enter and applying them to Emp1. At least, that's what I thought it was doing.
Was This Post Helpful? 0
  • +
  • -

#9 Skydiver  Icon User is offline

  • Code herder
  • member icon

Reputation: 5894
  • View blog
  • Posts: 20,114
  • Joined: 05-May 12

Re: Embed one struct within another

Posted 28 June 2013 - 03:00 PM

Since you are playing with struct's right now with public members, you probably aren't seeing the value. Later when you start writing more classes with private members, you'll want to change the state of the members through methods (or properties with public setters). So Curtis Rutland is trying to get you into the habit of using methods instead of accessing public members.

This post has been edited by Skydiver: 28 June 2013 - 03:01 PM

Was This Post Helpful? 0
  • +
  • -

#10 Semus  Icon User is offline

  • D.I.C Head

Reputation: 14
  • View blog
  • Posts: 126
  • Joined: 27-May 13

Re: Embed one struct within another

Posted 28 June 2013 - 03:07 PM

View PostSkydiver, on 28 June 2013 - 03:00 PM, said:

Since you are playing with struct's right now with public members, you probably aren't seeing the value. Later when you start writing more classes with private members, you'll want to change the state of the members through methods (or properties with public setters). So Curtis Rutland is trying to get you into the habit of using methods instead of accessing public members.


Then I'll just have to say that it's a bit over my head. My code example was simple for me to understand. If it gets any more complex than this, I'll have to do some more research on classes. I don't feel I have the proper understanding of classes given the fact that I don't understand Curtis's challenge at all.
Was This Post Helpful? 0
  • +
  • -

#11 Witchking  Icon User is offline

  • D.I.C Head

Reputation: 68
  • View blog
  • Posts: 189
  • Joined: 17-February 13

Re: Embed one struct within another

Posted 28 June 2013 - 03:42 PM

What Curtis Rutland and Skydiver were trying point out, is that it's generally bad practice to have public fields (variables) in a class, such as:
class Employee
{
	public string Name;
}
What you would mostly use what is called a property:
class Employee
{
	private string name;
	public string Name
	{
		get { return name; }
		set { name = value; }
	}
}
Basically a property has a getter and optionally a setter. The getter is called when you try to access Name, whereas the setter is called when setting the value of the property: Name = "Brian";. The benefit of using a property is not obvious here but consider the following:
class Child
{
	private int age;
	
	public int Age
	{
		get { return age; }
		set
		{
			if (value < 0) throw new ArgumentOutOfRangeException();
			else age = value;
		}
	}
}
Here if you try to set a value below zero an exception will be thrown because one cannot have a negative age.


For something more complex you might also use a method:
class Employee
{
	private string name;
	private DateTime dateOfBirth;
	
	public void SetValues(string name, DateTime, dateofbirth)
	{
		this.name = name;
		this.dateOfBirth = dateofbirth;
	}
}


You might also want to consider constructors. A constructor is a method that is called when the the class is instantiated. Constructors have no return type, and have the same name as the class. For example:
class Person
{
	private string name;
	private int age;
	
	public Person(string name, int age)
	{
		this.name = name;
		this.age = age;
	}
}
You would then instantiate this class like so:
void Main()
{
	Person p = new Person("Jack", 23);
}

This post has been edited by Witchking: 28 June 2013 - 03:53 PM

Was This Post Helpful? 0
  • +
  • -

#12 Semus  Icon User is offline

  • D.I.C Head

Reputation: 14
  • View blog
  • Posts: 126
  • Joined: 27-May 13

Re: Embed one struct within another

Posted 28 June 2013 - 04:06 PM

@WitchKing

I believe we're getting into the realm of "gibberish" again. What I am looking at isn't making any sense to me and that's not your fault, it's mine.

I'll just bring up a couple of questions and then I'll just let this one alone. I'm afraid I'm just too far out of my own comfort zone.

My first question is, why didn't you just write it out like this:

        public string someValue { get; set; }


My second questions is, what is this all about:
	private string name;
	public string Name


Why did you set name to Private and then set Name to public. I don't understand what you're trying to do there.

You don't really need to explain these things to me because chances are I won't understand it anyway. It was just something that caught my eye and couldn't make out (along with the rest of your code examples).
Was This Post Helpful? 0
  • +
  • -

#13 Witchking  Icon User is offline

  • D.I.C Head

Reputation: 68
  • View blog
  • Posts: 189
  • Joined: 17-February 13

Re: Embed one struct within another

Posted 28 June 2013 - 04:14 PM

private string name;

public string Name
{
	get { return name; }
	set { name = value; }
}

Name is a property. name is a field, a variable, namely a "backing variable" for the property Name. Name doesn't store any information, it's more of an interface for the variable behind it. The above piece of code is functionally equivalent to
public string Name { get; set; }
Here there is also a backing variable, only instead of being written by the programmer, it is handled by the compiler. So in essence there is no difference between the two. However the backing variable in the first piece of code becomes essential when you add logic to the property, like i showed in my previous post in the class Child.
Was This Post Helpful? 0
  • +
  • -

#14 Semus  Icon User is offline

  • D.I.C Head

Reputation: 14
  • View blog
  • Posts: 126
  • Joined: 27-May 13

Re: Embed one struct within another

Posted 28 June 2013 - 04:29 PM

Thanks for the explanation.

Why does it become essential when you add logic to the property, exactly? Your explanation will more than likely baffle me, but it's good for reference.


@Curtis Rutland

I'm sorry that I cannot do your challenge. I'm afraid I'm just not quite ready to take it on just yet. Perhaps in the future I'll come back to it when I have a better understanding of what you'd like me to do. I appreciate the challenge though. I'll keep chuggin away at this book and tutorials and maybe I'll be able to slowly get it.
Was This Post Helpful? 0
  • +
  • -

#15 Witchking  Icon User is offline

  • D.I.C Head

Reputation: 68
  • View blog
  • Posts: 189
  • Joined: 17-February 13

Re: Embed one struct within another

Posted 28 June 2013 - 04:35 PM

View PostSemus, on 29 June 2013 - 01:29 AM, said:

Why does it become essential when you add logic to the property, exactly?
Because you have to have something to refer to when setting the value:
private int age;

public int Age
{
	get { return age; }
	set
	{
		//value is the keyword you use to refer to the value being set
		//for example when you write: Age = 17;
		//here in the setter the value will be 17
		
		if (value < 0) throw new ArgumentOutOfRangeException();
		else age = value;
		//here you set the backing variable age to be equal to the value given
	}
}

Was This Post Helpful? 0
  • +
  • -

  • (2 Pages)
  • +
  • 1
  • 2