1

I learned basic and now I want to learn OOP in C# I have this code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace uceni_cs
{
    class Zdravic
    {
        public void pozdrav()
        {
            Console.WriteLine("Ahoj světe ! ");
        }
    }

}

But when I try to call it using this code

namespace uceni_cs
{
    class Zdravic
    {
        public void pozdrav()
        {
            Console.WriteLine("Ahoj světe ! ");
        }
    }
    Zdravic trida = new Zdravic();
}

In code Zdravic trida = new Zdravic(); is error. A namespace cannot directly contain members such as fields or methods. What I am doing wrong ? I just want to call the class. Thanks

6
  • 2
    You're instantiating a class outside of a class (inside of the namespace itself). You cannot do this. You need to instantiate it within another class somewhere. Commented Sep 30, 2016 at 10:54
  • 2
    Presumably you need to put that in your main() method Commented Sep 30, 2016 at 10:54
  • 2
    You cannot simply write executable statements on namespace or class level. This can only be done on method level. Try creating a new console application and call the line Zdravic trida = new Zdravic(); in the Main method when having written your class. Commented Sep 30, 2016 at 10:55
  • 1
    c# does not allow you to create global data and function within namespace. you can create objects and function in class or main methods Commented Sep 30, 2016 at 10:56
  • Thanks guys, works fine I just needed to put in my main :) Commented Sep 30, 2016 at 11:01

3 Answers 3

3

In C# there is no such a thing global variable so you can't just create new instance of Zdravic type that does not belong to any class.

I suggest you to read General Structure of a C# Program, and c# Classes and Structs.

Sign up to request clarification or add additional context in comments.

Comments

1

You need to create an entry point to your application and instantiate the class there.

class EntryPoint
{
    static void Main()
    {
        Zdravic trida = new Zdravic();

        trida.pozdrav();
    }
}

Comments

0

Create your class object in main method and then use the class properties using that object.

 Zdravic trida = new Zdravic();

in main method of you program/application.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.