C # beginner. Compiler errors - c#

I am new to C# and visual studio 2005
I created a new Console Application project in VS2005 and added a Class1.cs file to the existing Program.cs file that was created by default.
The Class1.cs file has the following simple code:
public class Class1
{
public Class1()
{
}
~Class1()
{
}
public void PrintMessage()
{
Console.WriteLine("\nHello\n");
Console.Read();
}
}
And program.cs file has the following:
class Program
{
static void Main(string[] args)
{
PrintMessage();
}
}
When I try to compile I get the following error:
The name 'PrintMessage' does not exist in the current context.
Any help?
Thanks, Viren

Try:
Class1 myClass = new Class1();
myClass.PrintMessage();
Or, what might be better since this seems like a utility function. Change your method definition to:
public static void PrintMessage()
So you can call it directly.
Class1.PrintMessage();

The name 'PrintMessage' does not exist in the current context.
It exists in another context - that of class Class1. Since it is a public function of that (public) class, you can use it, by creating an instance of Class1 (the PrintMessage function is not static, so you need an instance of Class1 to call it) and then invoking the PrintMessage function on it.
class Program
{
static void Main(string[] args)
{
Class1 someClass1Object = new Class1();
someClass1Object.PrintMessage();
}
}

PrintMessage is not a method of the class "Program", it's a method of Class1. Try
Class1 c = new Class1();
c.PrintMessage();
You probably also want to go through a tutorial or two :)

class Program
{
static void Main(string[] args)
{
new Class1().PrintMessage();
}
}
or make PrintMessage() to be static so you can use it next way:
public class Class1
{
public static void PrintMessage()
{
// ..
}
}
class Program
{
static void Main(string[] args)
{
Class1.PrintMessage();
}
}

You need a reference to the class where the method is. You must do that with:
Class1.PrintMessages();
Since Class1 is not static, you also need an instance of that class. You could do that with:
Class1 c = new Class1();
Finally, you have to call the method prefixed with the instance variable. Your code will look something like this:
Class1 c = new Class1();
c.PrintMessages();
If you want, you can shorten this code with the sentence
new Class1().PrintMessages();
that do the same as before.

Calling PrintMessage() inside of your Main function (which is a function on the Program class) means that the compiler is going to look for a function called PrintMessage() somewhere in the program class.
What you have is called an instance function on the Class1 class. In order to call this type of function, you need an instance of Class1 in your function. Something like this:
static void Main(string[] args)
{
Class1 myClass = new Class1();
myClass.PrintMessage();
}

Making the method static is probably what you want, rather than the other suggestions here:
public static void PrintMessage()
{
Console.WriteLine("\nHello\n");
Console.Read();
}
static tells the compiler that this method doesn't depend on an instance of a class. If that doesn't mean anything to you, read up on the topic of classes in your favourite C# book.

You need a reference to the Class1 class in order to call a method of the class. Try:
Class1 myClass = new Class1();
myClass.PrintMessage();

Your PrintMessage() method is a method of the Class1 class. You have to reference that class to get to the method.
class Program
{
static void Main(string[] args)
{
Class1 c = new Class1(); //Create an instance of your class
c.PrintMessage(); //Call the PrintMessage method of class Class1
}
}
Note: You may want to rename Class1 to something more descriptive.

Print message is not a part of Main:
u have to tell it where it is:
Class1 messageClass = new Class1();
messageClass.PrintMessage();

you need to reference the class that print message . . . AKA: Class1.PrintMessage()

Related

C# Class methods can't see objects created in same class's Main()

This is probably something really basic, but I'm not sure what's wrong:
partial class Program {
static void Main(string[] args) {
ADAttributes allObjectAttributes = new ADAttributes("AllObjects");
}
static void calcs() {
var x = allObjectAttributes; // <--- Name does not exist in the current context
}
}
Why is the calcs() method unable to see allObjectAttributes that was created in Main()?
Because C# does not work that way. The scope of the variable allObjectAttribute is to the Main-method, only in that method is the variable visible/usable.
If you want to have access to the variable from another method, you have to create a class field, and in your case, a static one.

How to instantiate non-static data items in static main() [duplicate]

This question already has answers here:
How do I call a non-static method from a static method in C#?
(11 answers)
Closed 5 years ago.
I have a C# console app with a static main method.
I want to be able to call a non-static method in main but
cannot.
I believe I need to keep main static but I also want to
run non-static methods within the program?
The statement below says an object reference is required.
c1 = new Class1()
Where / how do I instantiate non-static objects in this program?
Thanks
namespace VER
{
class Example
{
private Dictionary<string, long> dStrLong;
Class1 c1;
static void Main(string[] args)
{
c1 = new Class1();
}
}
}
If you make Class1 c1 static, you will be able to assign new object to it and call its non-static method.
Alternatively, remove Class1 c1 field from the class and write Class1 c1 = new Class1();.
I think you need to understand how this works behind the scenes.
When you use a static method, a silent instance is created for you and that is the instance that serves the calls to static methods.
Anything that is not static, belongs to each and every instance you create. That is why the compiler is saying an object reference is required (c1 is declared as an instance member).
In order for you to consume c1 within main, you can either make it static as well or make it a public member and create an instance so you can use it:
namespace VER
{
class Example
{
private Dictionary<string, long> dStrLong;
//You can make it static
static Class1 c1 = new Class1();
static void Main(string[] args)
{
c1.DoSomething();
}
}
}
OR
namespace VER
{
class Example
{
private Dictionary<string, long> dStrLong;
//You can make it public
public Class1 c1 = new Class1();
static void Main(string[] args)
{
var c1 = new Example();
c1.DoSomething();
}
}
}
As your code currently exists, you are trying to access a variable that belongs to an instance from a static method.
Either way, make sure you instantiate an object for the variable.

Error - the program is not giving output while calling the print method

This is a simple program I created - one table class, one main class. In the table class I created a print method which simply outputs my name. From the main class I am calling the print method but not getting the output.
namespace ConsoleApplication3
{
class table
{
public static void print()
{
Console.WriteLine("My name is prithvi-raj chouhan");
}
}
class Program
{
public static void Main()
{
table t = new table();
t.print(); // Error the program is not giving output while calling the print method
}
}
}
Since the function you are calling is static.
Use this syntax
public static void Main()
{
table.print();
}
Quote from MSDN:-
A static method, field, property, or event is callable on a class even
when no instance of the class has been created. If any instances of
the class are created, they cannot be used to access the static
member. Only one copy of static fields and events exists, and static
methods and properties can only access static fields and static
events. Static members are often used to represent data or
calculations that do not change in response to object state; for
instance, a math library might contain static methods for calculating
sine and cosine.
print is a static method, so call it as a static method:
public static void Main()
{
table.print();
}
try this:
class Program
{
public static void Main()
{
table.Print();
}
}
Print(); is a static method so you dont need to instantiate a new Table object in order to access it's methods
You are calling print() as an instance method but it is static. Try to remove the static keyword from the method.
Try to add a Console.ReadLine(); after table.print();.
UPDATE:
Missed the part with static, now corrected.

OOP - how to call a function before the class constructor

I have a job interview tomorrow and I'm trying to answer this question:
There is a class named C and method m in this class, this class have also empty constructor:
Main ()
{
C c = new c();
}
Class C {
public c {
//empty constructor
}
public m {
//does something - doesnt mind
}
}
And what you have to do is to change the code so that in a creation of an instance class C, the method m would be called before the class constructor.
You have to do this without changing the main (edit only the class code).
Thanks in advance!
Like the other answers have said, you can make the method static. But then you need to explicitly call it. If you make a static class constructor, that will get called once automatically (you don't need to call it), the first time the class is referenced (like when you construct the first instance). You can't exactly control when it executes, but it will execute before the first instance is constructed. Based on the way they've worded the question (you can't change the Main method), I think static class constructor is the answer they're looking for.
http://msdn.microsoft.com/en-us/library/k9x6w0hc%28v=vs.80%29.aspx
Static constructors have the following properties:
A static constructor does not take access modifiers or have parameters.
A static constructor is called automatically to initialize the class before the first instance is created or any static members are
referenced.
A static constructor cannot be called directly.
The user has no control on when the static constructor is executed in the program.
Java doesn't have static class constructors, but they do have static initialization blocks..
static {
// code in here
}
To call a class's method before its constructor gets called you either have to turn this method into static so you don't need an instance of that class to call it, or (in C#) you can use FormatterServices.GetUninitializedObject Method to get an instance of your class without running the constructor (which of course may not be a wise thing to do).
In JAVA:
make method static and call your method in static block.
class C{
static{
m();
}
public C() {
System.out.println("Constructor Called..");
}
public static void m() {
System.out.println("m() is called.");
}
}
Main call
public static void main(String[] args) {
new C();
}
In both Java and C# you can use, base class constructors, static constructors (Edit: static initializer block in Java), and field initializers, to call code before the C class's constructor executes without modifying Main.
An example using a field initializer block in Java:
class C {
{ m(); }
public C() {
System.out.println("cons");
}
public void m() {
System.out.println("m");
}
}
This prints "m", then "cons". Note that m is called every time a C is constructed. A static initializer block would only be called once for the JVM.
Its basic OOP. You have to make a public static method and call it. That method can then call the constructor, or you can call the constructor directly from main.
Before you call the constructor, the object don't exist, therefore no instance methods exist, therefore nothing tied to the instance/object can be called. The only things that do exist before the constructor is called is the static methods.
Following way seems to achieve what is required. Without using static methods/variables
namespace FnCallBeforeConstructor
{
static void Main(string[] args)
{
MyClass s = new MyClass();
Console.ReadKey();
}
partial class MyClass: Master
{
public override void Func()
{
Console.WriteLine("I am a function");
}
public MyClass()
: base()
{
Console.WriteLine("I am a constructor");
}
}
class Master
{
public virtual void Func() { Console.WriteLine("Not called"); }
public Master()
{
Func();
}
}
}
Output is:
I am a function
I am a constructor

How to call a method from a different class

At the moment I have created a new method in a new class, and I am trying to call this method from my main class:
Program.cs:
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
testing();
Console.ReadLine();
}
}
}
and the method is in "Class1.cs":
namespace ConsoleApplication2
{
class Class1
{
public static void testing()
{
System.Console.WriteLine("It works!");
}
}
}
You need to specify the name of the class that the method is on. So:
Class1.testing();
Sometimes you might of course need to also worry about the namespace that Class1 is in. In this case both Class1 and Main are in the same namespace. If they hadn't been though then you'd have had to call it like:
ConsoleApplication2.DifferentNamespace.Class1.testing();
or with a using declaration at the top of program.cs:
using ConsoleApplication2.DifferentNamespace
You have made testing a static method, so you can call the method in this fashion
static void Main(string[] args)
{
Class1.testing();
Console.ReadLine();
}
Is this what you want ?
You are missing the class declaration in order to use the static method:
Class1.testing();
Class 1 has to be a public class and then you can call Class1.testing()

Categories