|
-
December 22nd, 2009, 06:00 AM
#1
total n00b question
I'm learning c# and having some trouble understanding implementation of classes.
Below is a simple program i was writing to use classes. it takes your name and age, stores them in a class and displays them.
Code:
// Namespace Declaration
using System;
public class CTest1
{
private string m_name;
private int m_age;
public string Name
{
get { return m_name; }
set { m_name = value; }
}
public int Age
{
get { return m_age; }
set { m_age = value; }
}
}
public class CMain
{
public static void Main()
{
CTest1 aTest = new CTest1();
Console.WriteLine("Please Enter Name");
aTest.Name = Console.ReadLine();
Console.WriteLine("Please Enter Age");
aTest.Age = Int32.Parse(Console.ReadLine());
Console.Clear();
//CTest1 aTest = new CTest1();
Console.WriteLine("Your Name is: {0}", aTest.Name);
Console.WriteLine("You are: {0} years old.", aTest.Age);
}
}
that code works fine.
so i split it up. i want individual methods to perform the input and out put so i split it up like this:
Code:
using System;
public class CTest1
{
private string m_name;
private int m_age;
public string Name
{
get { return m_name; }
set { m_name = value; }
}
public int Age
{
get { return m_age; }
set { m_age = value; }
}
}
public class CMain
{
public static void Main()
{
CTest1 aTest = new CTest1();
CMain.getInput();
CMain.showOutput();
Console.ReadLine();
}
public static void getInput()
{
Console.WriteLine("Please Enter Name");
aTest.Name = Console.ReadLine();
Console.WriteLine("Please Enter Age");
aTest.Age = Int32.Parse(Console.ReadLine());
}
public static void showOutput()
{
Console.Clear();
Console.WriteLine("Your Name is: {0}", aTest.Name);
Console.WriteLine("You are: {0} years old.", aTest.Age);
}
}
now I get 4 errors, one each where i've referenced my object 'aTest', the error is: 'aTest' does not exist in current context.
how can i access my object from multiple methods. If i have to keep coming back to Main() to call the properties from my object it seems like it defeats the purpose of OOP.
I use VB .Net primarily, and once an object is initialized, as long as it's public, it is callable from all sub routines. Can someone help me make this connection please.
Last edited by PyrexKidd; December 23rd, 2009 at 03:52 PM.
-
December 22nd, 2009, 06:16 AM
#2
Re: total n00b question
How do you expect a local variable declared in a function Main to be accessible in diff function ? to do that the variable has to be class member(of CMain).
Regards,
Ramkrishna Pawar
-
December 22nd, 2009, 06:22 AM
#3
Re: total n00b question
 Originally Posted by PyrexKidd
I'm learning c# [...]
your next step is to learn how to use the "code" tags in forums like this.
and to your problem... the aTest variable must be a field if you want to use it class-wide.
Code:
public class CMain
{
CTest1 aTest = new CTest1(); // this is a field
public static void Main()
{}
}
you should also review the part in your tutorial or book about variable scope etc.
Last edited by memeloo; December 22nd, 2009 at 06:25 AM.
win7 x86, VS 2008 & 2010, C++/CLI, C#, .NET 3.5 & 4.0, VB.NET, VBA... WPF is comming
remeber to give feedback  you think my response deserves recognition? perhaps you may want to click the Rate this post link/button and add to my reputation
private lessons are not an option so please don't ask for help in private, I won't replay
if you use Opera and you'd like to have the tab-button functionality for the texteditor take a look at my Opera Tab-UserScirpt; and if you know how to stop firefox from jumping to the next control when you hit tab let me know
-
December 22nd, 2009, 06:25 AM
#4
Re: total n00b question
how can i access my object from multiple methods
You have two options:
1. Pass the object to each method that needs it
Code:
private static void showOutput(CTest1 test)
{
}
2. As Krishnaa said declare a variable that is within the scope of the method. In this a class-level variable.
Code:
public class CMain
{
private CTest1 aTest;
public static void Main()
{
aTest = new CTest1();
CMain.getInput();
CMain.showOutput();
Console.ReadLine();
}
A few things to notice:
1. I made the showOutput method private and the aTest field private. Don't make any members public unless you need to.
2. You can use code tags to format your code within the post. It makes it easier for others to read and hopefully help you.
-
December 22nd, 2009, 06:27 AM
#5
Re: total n00b question
it looks like all 3 of us was writing their replays at the same time
win7 x86, VS 2008 & 2010, C++/CLI, C#, .NET 3.5 & 4.0, VB.NET, VBA... WPF is comming
remeber to give feedback  you think my response deserves recognition? perhaps you may want to click the Rate this post link/button and add to my reputation
private lessons are not an option so please don't ask for help in private, I won't replay
if you use Opera and you'd like to have the tab-button functionality for the texteditor take a look at my Opera Tab-UserScirpt; and if you know how to stop firefox from jumping to the next control when you hit tab let me know
-
December 22nd, 2009, 06:30 AM
#6
Re: total n00b question
 Originally Posted by memeloo
you should also review the part in your tutorial or book about variable scope etc.
This is a very good point. Often overlooked by many people starting out.
PyrexKidd:
- Get yourself a book. You can buy one or borrow one. It doesn't need to cover the latest version of C# or .NET as it looks like you still need to go through general procedural programming and object oriented programming. There are also many tutorials on the web. Books for me are best if you're a beginner as they provide a good structure, introduce to the concepts in a gradual manner. Also you can use MSDN.
-
December 22nd, 2009, 06:31 AM
#7
Re: total n00b question
 Originally Posted by memeloo
it looks like all 3 of us was writing their replays at the same time 
Yeah. We're all very willing to help!!!
-
December 22nd, 2009, 07:16 PM
#8
Re: total n00b question
It scares me that you are programming software, and you don't even know how to use [code] tags.
-
December 23rd, 2009, 04:13 AM
#9
Re: total n00b question
haha. you ever have one of those aww **** moments... lol...
Code:
it's not that I don't know...
a lot has changed from:
[color=White]
Code:
10 PRINT "Hello World!"
20 PRINT "This is line two."
15 PRINT "Oops... This is Line Two..."
[/color=white]
or
Code:
$ SET SOURCEFORMAT"FREE"
IDENTIFICATION DIVISION.
PROGRAM-ID. DoesAnyoneUseThis.
PROCEDURE DIVISION.
DisplayPrompt.
DISPLAY "Does anyone even use this anymore".
STOP RUN.
(ok i had a little help with my COBOL...)
so the challenge was to take a series of inputs add them all together add the tax and give a total.
I did this in VB (it was a VB class) rather easily and then did it in VB using classes, which required a few more lines.
so the way i did it in VB was like this:
Code:
Option Explicit On
Option Compare Text
Module Module1
Sub Main()
Dim itemPrice(0 To 1) As Double, i As String,
taxPrice As Double, itemLocation As Integer = 1,
itemSize As Integer, subTotal As Double,
total As Double
Const TAXRATE As Double = 0.0825
Console.ForegroundColor = ConsoleColor.DarkGreen
Console.WriteLine("Enter Prices")
Console.WriteLine("enter T to total")
Console.WriteLine("Tax Rate is an assumed 8.25%")
i = Console.ReadLine()
Do While (1)
If i <> "t" Then
ReDim Preserve itemPrice(0 To itemLocation)
itemPrice(itemLocation) = Double.Parse(i)
itemSize = itemLocation
itemLocation = itemLocation + 1
Else
Exit Do
End If
i = Console.ReadLine()
Loop
itemLocation = 1
Do While itemLocation <= itemSize
subTotal = subTotal + itemPrice(itemLocation)
itemLocation = itemLocation + 1
Loop
taxPrice = subTotal * TAXRATE
total = taxPrice + subTotal
itemSize = itemLocation
itemLocation = 1
Do While (itemLocation < itemSize)
Console.WriteLine("Item: {0}", itemPrice(itemLocation))
itemLocation = itemLocation + 1
Loop
Console.WriteLine("")
Console.WriteLine("Subtotal: {0}", subTotal)
Console.WriteLine("Total Tax Ammount {0}", Math.Round(taxPrice))
Console.WriteLine(" _____________")
Console.WriteLine("Total Price: {0}", Math.Round(total))
Console.ReadLine()
End Sub
End Module
'with the tabs in vs the output lines up perfectly. i've done my best to line it up here
i've found a few answers how to do this in c# mostly using the arrayCopy(); command, but i'm not sure how to implement this, and msdn only helps to confuse me. I'm really not looking for you to write the code for me, but perhaps you could point me in the right direction.
or maybe there's an even better approach?
Also maybe you could provide some ideas on how to write this using separate classes. personally I'd think one class would have all of the information and the Main() would handle all of the calls to the class(though this does seem rather inefficient doesn't it?)
perhaps you could recommend a good tutorial? and perhaps some better exercises? as (i think...) I mentioned I'm the starving college student type so perhaps not super expensive books...
thanks for all your help.
-
December 23rd, 2009, 04:17 AM
#10
Re: total n00b question
and my variable declarations are worse than TERRIBLE but it was late... they worked for me ok!!! haha.
-
December 23rd, 2009, 11:43 AM
#11
Re: total n00b question
 Originally Posted by Mr. Jones
It scares me that you are programming software, and you don't even know how to use [code] tags.
I think this is a bit harsh as demonstrated by later posts by PyrexKid. The forum allows you to post content without all the formatting that could make it prettier. The forum also allows users to post without necessarily going through the FAQs. I suspect that a few people just go straight to the point and post because they're looking for an aswer to the problem they're facing. Not knowing how to use Codeguru code tags (on its own or if at all) is not an indication of a person's ability to write software programs. Just for the record I almost always point out the missing code tags whenever I come across them. That way a person can look them up and use them from then onwards. If they insist on not using them even though they know about them that is a different issue. But still not an indication on its own of a person's ability to write software programs...
-
December 23rd, 2009, 11:58 AM
#12
Re: total n00b question
 Originally Posted by PyrexKidd
i've found a few answers how to do this in c# mostly using the arrayCopy(); command, but i'm not sure how to implement this, and msdn only helps to confuse me. I'm really not looking for you to write the code for me, but perhaps you could point me in the right direction.
or maybe there's an even better approach?
Also maybe you could provide some ideas on how to write this using separate classes. personally I'd think one class would have all of the information and the Main() would handle all of the calls to the class(though this does seem rather inefficient doesn't it?)
perhaps you could recommend a good tutorial? and perhaps some better exercises? as (i think...) I mentioned I'm the starving college student type so perhaps not super expensive books...
1. There are many different ways of accomplishing the generic goal that you've stated. E.g. not using a console app or sticking with the console app and allowing the user the enter a series of prices separated by commas, spaces, etc. You can let the user give you the data in a text file and you read it from there...the options are many
2. You could still have a separate class that contains the fundamental aspect of what you are doing (i.e. adding numbers, applying a tax and outputing the results). Here's a simple possibility. There are many improvements that can be made but this is where I would start if I were in your position.
Code:
public class TaxUtility
{
private double _taxRate = 0.0825;
private double[] _prices;
public TaxUtility(double[] prices)
{
_prices = prices;
}
public double GetTotal()
{
// Iterate through the array of prices and add them.
// Apply the tax and return result.
}
public double GetSubTotal()
{
// Iterate through the array of prices and add them and return the total.
}
public double GetTax()
{
}
}
3. Doing all the coding/logic in the Main method doens't make it inneficient but it could make it difficult to change and maintain. the benefit of separating the logic into different methods or another class is that you can minimise the impact of the change and minimise and localise any potential errors.
4. There's probably a library nearby where you could borrow the books you need. You wouldn't need many and you wouldn't need them for a long time. Again MSDN can take you through most of the basics but they will not provide an in depth introduction into object oriented programming but they'll do a good job of it.
Last edited by nelo; December 23rd, 2009 at 11:59 AM.
Reason: Formatting...
-
December 23rd, 2009, 03:51 PM
#13
Re: total n00b question
ok so here is what i came up with to do the same thing in C#.
I did all the computation in the Main() method to simplify and decrease coding time.
now the only problem is when i try to view the contents of my array I receive an error that i must make sure i'm trying to view a part of the array outside of it's parameters.
the code is pretty much the same as my VB code except the part with the array.
Any Thoughts?
Code:
using System;
namespace taxRate
{
class Program
{
static void Main(string[] args)
{
double[] itemList = new double[2];
double itemSubTotal = 0.0;
int itemLocation = 1 ;
int itemMaxSize = 1;
double taxPrice = 0.0;
string input = "A";
double taxRate = 0.0825;
double totalPrice = 0.0;
Console.ForegroundColor = ConsoleColor.DarkGreen;
Console.WriteLine("Enter The Items.");
Console.WriteLine("Enter T to Total");
input = Console.ReadLine();
while (input != "T" || input != "t")
{
if (input == "T" || input == "t")
{ break; } //end if
else if (double.Parse(input) >= 0 || double.Parse(input) <= 0)
{
itemList[itemLocation] = double.Parse(input);
itemLocation++;
itemMaxSize = itemLocation;
Array.Resize(ref itemList, itemList.Length + 1);
input = Console.ReadLine();
}
else
{
Console.WriteLine("Please Reenter Your Number");
input = Console.ReadLine();
}
}//end loop
Array.Resize(ref itemList, 1);
itemLocation = 1;
Console.Clear();
while (itemLocation <= itemMaxSize)
{
Console.WriteLine("Your Item: {0}", itemList[itemLocation]);
itemSubTotal = itemSubTotal + itemList[itemLocation];
itemLocation++;
}//end loop
taxPrice = itemSubTotal * taxRate;
totalPrice = itemSubTotal + taxPrice;
Console.WriteLine("The Price of Tax Is: {0}", Math.Round(taxPrice, 2));
Console.WriteLine(" __________");
Console.WriteLine("The Total Price Is: {0}", Math.Round(totalPrice, 2));
Console.ReadLine();
}//End Main
}// End Class
}//End Program
oh and i ment to ask
Code:
public class TaxUtility
{
private double _taxRate = 0.0825;
private double[] _prices;
public TaxUtility(double[] prices)
{
_prices = prices;
}
is using the the same as naming it to signify that it is a member of the class?
-
December 24th, 2009, 05:23 AM
#14
Re: total n00b question
 Originally Posted by PyrexKidd
now the only problem is when i try to view the contents of my array I receive an error that i must make sure i'm trying to view a part of the array outside of it's parameters.
the code is pretty much the same as my VB code except the part with the array.
I suspect it is because you initialise itemLocation = 1. Arrays are zero-based. So if an array has 5 elements you index it 0, 1, 2, 3, 4.
There is no difference between _taxRate and m_taxRate. It is just naming convention to indicate member fields as you said. I use the m_ (unless I really have to) because it seems like a carry over from C++. I love C++ but when I'm coding in C# I try to stay true to C# coding style.
-
December 25th, 2009, 04:36 PM
#15
Re: total n00b question
I suspect it is because you initialise itemLocation = 1. Arrays are zero-based. So if an array has 5 elements you index it 0, 1, 2, 3, 4.
I understand arrays are zero based but if you initialize an array of size 2 you can put a value in location 1 and location 0 would be null for all intents and purposes.
see code:
Code:
dim thisArray(0 to 1) as int
this array(1) = 100
thisArray(0) essentially equals null or nonexistent
thisArray(1) equals 100 and there is no
thisArray(2)
right?
now i understand C# is a different language and i have to learn the special nuances of each new language, so i guess really my question is:
Do i HAVE to declare array location 0 every time? What if i declared my array
Code:
int[] itemList = New itemList[2];
itemList[0] = 0
(the declaration new itemLIst[2] means from 0 to 1 right?)
and then from there i can use locations 1-10.
maybe I'm missing some fundamental of arrays, but I think this seems logical.
Unfortunately I had a nasty spill with my computer so I don't have access to my programming environment for a couple weeks while I send it in for service/repair/replacement... I'd rather actually coding to find my answer.
I use the m_ (unless I really have to) because it seems like a carry over from C++.
what does this mean? do you mean you don't use the m_ unless you have to?
I'm not trying to flame you, just trying to understand.
and why do you say it's from C++ b/c i learned that naming convention from a teacher who just professed his love for VB.
(seriously sit thru a few years of "OH VB is so GREAT!!!")
thanks for all your help guys/gals it's been great. I really do appreciate it.
Merry New Year and Happy Xmas
and a Happy Chanukah
Last edited by PyrexKidd; December 25th, 2009 at 04:43 PM.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|