Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

Object Oriented Programming with C#

Posted on 2011-03-17
12
Medium Priority
?
356 Views
Last Modified: 2012-05-11
I created a new class called Person and when I declared the class in Person.cs, I get this code that is automatically generated:

 public Person()
          {
       
       

            //
            // TODO: Add constructor logic here
            //
          }

I don't see the reason for having this in my code, in fact I get the following error when I have it included in my code: Unexpected modifier.

Why does this get automatically generated and do I need it or can I just erase it.  Please see my class and tell me if this is how you do object oriented programming in C#.  Below is my final code of my Person class after I deleted the unexpected modifier, is this correct on how to create an object?

 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

/// <summary>
/// Summary description for Person
/// </summary>
/// 

public class Person
{
    public string Name { get; set; }
    public string Surname { get; set; }


    public int Age
    {
        get
        {
            return Age;
        }
        set
        {
            if (value < 1 || value > 100)
            {
                throw new Exception("Invalid age");
            }
            Age = value;
        }

    }

    public decimal Height
    {
        get
        {
            return Height;
        }
        set
        {
            if (value < 1.00M || value > 2.40M)
            {
                throw new Exception("Invalid height");
            }
            Height = value;
        }
    }

    public decimal Weight
    {
        get
        {
            return Weight;
        }
        set
        {
            if (value < 30 || value > 240)
            {
                throw new Exception("Invalid weight");
            }        
        Weight = value;
    }

    
	   
    }
}

Open in new window

0
Comment
Question by:VBBRett
  • 5
  • 4
  • 3
12 Comments
 
LVL 8

Expert Comment

by:crysallus
ID: 35162657
You shouldn't have got an unexpected modifier error from just having that code included. I noticed that your bracketing is a little out at the end of the Weight property. If you had that code between the third last and second last closing curly brackets, that could very well have produced the error, but that's because the bracketing for the Weight property is out, in which case that code would have been inside that property's code block - definitely not the right thing to do.
0
 
LVL 13

Accepted Solution

by:
hiteshgoldeneye earned 1000 total points
ID: 35162669
Every class that is created calls a method called constructor when you instantiate the class (i.e. when you create an instance of the class). The default constructor (which has been automatically added in your case) contains no code and can be omitted, but you can add code within a constructor to initialize the fields.

The class that you have provided is a bit incorrect as the properties like Age, Height, Weight that you have created are accessing themselves in the definition. You need to create corresponding fields. I think this might be due to the confusion of shorthand code introduced in .NET 3.5. Please have a look at link below
http://forums.asp.net/t/1191140.aspx/1?C+NET+class+getter+setter+shorthand

A class generally has some private fields and exposes these fields via public properties. This is one of the main feature of object oriented programming called as Encapsulation

Also there is a certain order of putting content into your class discussed in the link below
http://stackoverflow.com/questions/150479/order-of-items-in-classes-fields-properties-constructors-methods

Please have a look at my code below and hope this helps-


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

/// <summary>
/// Summary description for Person
/// </summary>
/// 

public class Person
{
    private int _age;
    private decimal _height;
    private decimal _weight;
    public string Name { get; set; }
    public string Surname { get; set; }


    public int Age
    {
        get
        {
            return _age;
        }
        set
        {
            if (value < 1 || value > 100)
            {
                throw new Exception("Invalid age");
            }
            _age = value;
        }

    }

    public decimal Height
    {
        get
        {
            return _height;
        }
        set
        {
            if (value < 1.00M || value > 2.40M)
            {
                throw new Exception("Invalid height");
            }
            _height = value;
        }
    }

    public decimal Weight
    {
        get
        {
            return _weight;
        }
        set
        {
            if (value < 30 || value > 240)
            {
                throw new Exception("Invalid weight");
            }        
        _weight = value;
    }

    
	   
    }
}

Open in new window

0
 

Author Comment

by:VBBRett
ID: 35162771
How does this look now gentlemen?  I even added a method at the end:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

/// <summary>
/// Summary description for Person
/// </summary>
///

public class Person
{
    public string Name { get; set; }
    public string Surname { get; set; }
    private int age;
    private decimal height;
    private decimal weight;

    public int Age
    {
        get
        {
            return age;
        }
        set
        {
            if (value < 1 || value > 100)
            {
                throw new Exception("Invalid Age");
               
            }
            age = value;
        }

    }

    public decimal Height
    {
        get
        {
            return height;
        }
        set
        {
            if (value < 1.00M || value > 2.40M)
            {
                throw new Exception("Invalid height");
            }
            height = value;
        }
    }

    public decimal Weight
    {
        get
        {
            return weight;
        }
        set
        {
            if (value < 30 || value > 240)
            {
                throw new Exception("Invalid weight");
            }        
        weight = value;
    }

   
        
    }

    public int CalculateAge(DateTime birthDate)
    {
        DateTime now = DateTime.Today;
        int years = now.Year - birthDate.Year;
        if (now.Month < birthDate.Month || (now.Month == birthDate.Month && now.Day < birthDate.Day))
        {
            years = years - 1;
        }




        return years;

    }
   
   
}
0
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

 

Author Comment

by:VBBRett
ID: 35162776
Now the modifier that I omitted in my code that I previously mentioned in my first post, should I put it back into my Class?
0
 
LVL 13

Expert Comment

by:hiteshgoldeneye
ID: 35162803
Looks good to me :), as mentioned the constructor code is optional, your class should work fine without it too, however you can add it if you feel you might want to add code to initialize the fields in your class.
0
 
LVL 8

Expert Comment

by:crysallus
ID: 35162825
As long as you are happy to have all your class member fields initialised according to the defaults listed here, then you don't need to define your own constructor, the default one provided for you will suffice.
0
 
LVL 8

Assisted Solution

by:crysallus
crysallus earned 1000 total points
ID: 35162834
The default one provided by the system that is, in the event that your code doesn't contain any constructors at all, not the "default" one created for you by the code wizard which is what you are asking about.

In short, the answer is no. Sorry for fluffing the explanation...
0
 

Author Comment

by:VBBRett
ID: 35162861
Thank you very much gentlemen, I will be splitting the points evenly between you both.  One question that I have for you both and you don't have to answer the question but i am curious as to how to set values for my birthdate method when I am writing code.  Nothing I put into my values seems to jive with the code that I wrote for that method.  Do I write the month, year, day?  Do I put text or do I put numbers?  
0
 
LVL 13

Expert Comment

by:hiteshgoldeneye
ID: 35162880
If you are talking about taking input from a user, you should ideally provide a calendar control to select the birthdate. http://www.asp.net/ajax/ajaxcontroltoolkit/samples/calendar/calendar.aspx
The control populates a textbox to which it is attached and you can get the selected date.
0
 

Author Comment

by:VBBRett
ID: 35162890
Is there a way to do this date input with text?  I am just running a test to see if my method works before I start using any kind of web interface controls.  Thanks!
0
 

Author Comment

by:VBBRett
ID: 35162895
Anyways, answer the question I just posted at your own leisure.  You guys are awesome, I am posting the points now.  I am well on my way now to becoming a real object oriented programmer.  Thanks guys!
0
 
LVL 13

Expert Comment

by:hiteshgoldeneye
ID: 35162910
I assume you want to call your CalculateAge method with a valid datetime, you can try the following

DateTime birthdate = new DateTime(1990, 1, 18);
Person A = new Person();
int age = A.CalculateAge(birthdate);

Some links on datetime
http://www.dotnetperls.com/datetime-1
http://programming.top54u.com/post/C-DateTime-Format-String.aspx

Let me know if this is what you meant and Good luck for the way ahead :)
0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article is for Object-Oriented Programming (OOP) beginners. An Interface contains declarations of events, indexers, methods and/or properties. Any class which implements the Interface should provide the concrete implementation for each Inter…
This article aims to explain the working of CircularLogArchiver. This tool was designed to solve the buildup of log file in cases where systems do not support circular logging or where circular logging is not enabled
This course is ideal for IT System Administrators working with VMware vSphere and its associated products in their company infrastructure. This course teaches you how to install and maintain this virtualization technology to store data, prevent vuln…
In response to a need for security and privacy, and to continue fostering an environment members can turn to for support, solutions, and education, Experts Exchange has created anonymous question capabilities. This new feature is available to our Pr…
Suggested Courses

971 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question