Click to See Complete Forum and Search --> : total n00b question
PyrexKidd
December 22nd, 2009, 05:00 AM
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.
// 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:
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.
Krishnaa
December 22nd, 2009, 05:16 AM
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).
memeloo
December 22nd, 2009, 05:22 AM
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.
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.
nelo
December 22nd, 2009, 05:25 AM
how can i access my object from multiple methods
You have two options:
1. Pass the object to each method that needs it
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.
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.
memeloo
December 22nd, 2009, 05:27 AM
it looks like all 3 of us was writing their replays at the same time :p
nelo
December 22nd, 2009, 05:30 AM
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.
nelo
December 22nd, 2009, 05:31 AM
it looks like all 3 of us was writing their replays at the same time :p
Yeah. We're all very willing to help!!! :D
Mr. Jones
December 22nd, 2009, 06:16 PM
It scares me that you are programming software, and you don't even know how to use [code] tags.
PyrexKidd
December 23rd, 2009, 03:13 AM
haha. you ever have one of those aww **** moments... lol...
it's not that I don't know...
a lot has changed from:
10 PRINT "Hello World!"
20 PRINT "This is line two."
15 PRINT "Oops... This is Line Two..."
[/color=white]
or
$ 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:
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
[color=green]'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.
PyrexKidd
December 23rd, 2009, 03:17 AM
and my variable declarations are worse than TERRIBLE but it was late... they worked for me ok!!! haha.
nelo
December 23rd, 2009, 10:43 AM
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...
nelo
December 23rd, 2009, 10:58 AM
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.
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.
PyrexKidd
December 23rd, 2009, 02:51 PM
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?
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
public class TaxUtility
{
private double _taxRate = 0.0825;
private double[] _prices;
public TaxUtility(double[] prices)
{
_prices = prices;
}
is using the _taxRate the same as naming it m_taxRate
to signify that it is a member of the class?
nelo
December 24th, 2009, 04:23 AM
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.
PyrexKidd
December 25th, 2009, 03:36 PM
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:
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
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
nelo
December 26th, 2009, 09:11 AM
Hi PyrexKidd,
Thanks for correcting that. I meant to say I DON'T use "m_ " to prefix class fields unless I have really have to (e.g. I'm working in a class that already uses that convention, my boss/team leader says I should do it that way, etc)
Arrays...
If you define a fixed size array you can only index the elements within the array boundaries and they have zero-based indexes:
int[] sizes = new int[2];
sizes[0] = 45; // Indexing the first (sometimes called the zeroth element).
sizes[1] = 47; // Indexing the second element.
sizes[2] = 49; // This should produce an exception because we are trying to index into an element that is not there, i.e. it is beyond the array boundaries.
If you don't want to use the zeroth element (e.g. sizes[0]) that's up to you though that would be an odd thing to do. For example if you need 10 elements in your array following your logic you would define it like this:
int[] sizes = new int[11];
// You can ignore the zeroth element if you will but that is not the C# way in general.
// This becomes important if someone uses that array in some other code without knowing // // your convention.
sizes[1] = 1;
...
sizes[10] = 10;
To answer your question more directly if you define an array such as sizes[2] you cannot access elements 2 - 10. You can access 0 and 1 as the array only has two elements.
Hope this makes things clearer. It would be beneficial to you if you could borrow a book from the library or check out some of the general C# concepts in MSDN. Folks here at codeguru will be glad to help whenever they can on specific things.
Arjay
December 26th, 2009, 04:37 PM
and my variable declarations are worse than TERRIBLE but it was late... they worked for me ok!!! haha.If you are talking about the class fields (i.e what used to be called class variables), you're close. Just drop the 'm' prefix and you're good (e.g. m_name becomes _name).
codeguru.com
Copyright Internet.com Inc., All Rights Reserved.