-
Quick Question
Code:
using System;
namespace Testing {
class Class1 {
static string name = "Chris";
static int age = 19;
public string person = "Protected";
string person2 = "Private";
static void Main(string[] args) {
try {
Console.Write(name + " is " + age + " years old." + "\n");
Console.Write(person + "\n");
Console.Write(person2);
Console.ReadLine();
} catch (System.Exception e) {
Console.Write("Error: " + e);
}
}
}
}
Error I get:
C:\development\C#\Testing\Class1.cs(14): An object reference is required for the nonstatic field, method, or property 'Testing.Class1.person'
I'm just trying to experiment with some things in C#. Do I have to make everything static in order to use it? How can I create an object to use?
-
no you dont have to make everything static to use it
-
So I'll just declare (is that the correct term in C#?) the vars in the method (is that the correct term in C#?) where they are used.
-
declare or instantiate (either one will do)
although they have some what different meanings
to me they are the same, well kinda
either one will do
as for "methods" that is also correct to
methods or functions either one will do
what exactly are you trying to do herE?
-
I'm not really trying to do anything, just messing around. Here's what I have now.
Code:
using System;
namespace Testing {
class Class1 {
static void Action(int age, string name) {
try {
//would bring in name and age from textbox
Console.Write(name + " is " + age + " years old." + "\n");
} catch (System.Exception e) {
Console.Write("Error: " + e);
}
}
static void Information(string info) {
try {
//would bring info in from textbox
Console.Write(info);
} catch (System.Exception e) {
Console.Write("Error: " + e);
}
}
static void Main(string[] args) {
Class1.Action(19, "Chris");
Class1.Information("This would be from a TextBox in a WinForm.");
Console.ReadLine();
}
}
}
-
it looks good (havent tested the code for little bugs)
but anything in perticular yoru stock on or need help with?
When you make a method static in a class you dont have to instantiate (declare) a variable for that class in order to use it
you can just do Class1.mymethod
but if you dont make them static
you have to go something like
Class1 clsObject = new Class1();
clsbObject.mymethod();
-
Which is creating a new reference to the object. :)
You know, I swear I've seen this theory before from some other language. :p
-
if you ever have worked with Delphi, thats pretty much where .NET comes from
the person that made delphi is the person that made .net
ms gave him a 2.5 million sign up bonus (and God knows how much more)