Solved

Object Oriented Programming with C#

Posted on 2011-03-17
12
346 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 250 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
 

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
IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 
LVL 8

Assisted Solution

by:crysallus
crysallus earned 250 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

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

Suggested Solutions

Bit flags and bit flag manipulation is perhaps one of the most underrated strategies in programming, likely because most programmers developing in high-level languages rely too much on the high-level features, and forget about the low-level ones. Th…
This article introduced a TextBox that supports transparent background.   Introduction TextBox is the most widely used control component in GUI design. Most GUI controls do not support transparent background and more or less do not have the…
This video discusses moving either the default database or any database to a new volume.
Here's a very brief overview of the methods PRTG Network Monitor (https://www.paessler.com/prtg) offers for monitoring bandwidth, to help you decide which methods you´d like to investigate in more detail.  The methods are covered in more detail in o…

744 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

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now