Dot notation for class member access

I've got the following code:

public class Random
{
    public string Name { get; set; }

    public bool IsRunning()
    {
        var running = true;

        return running;
    }
}

public class Main
{
    Random newObject = new Random();

    newObject.Name = "Johnny";

    var result = newObject.IsRunning();
}

which all exists in the same .cs file in the same namespace. Any time I've created a new project before I've never had to set up anything to use dot notation to access member attributes or methods, but this is saying that I can't use newObject. ANYTHING, and also that "var" is not valid for a keyword. It's a windows forms application like I normally use, but I'm drawing blanks here as why I can't do all these things that I normally use many times in my other programs. What am I missing here?

Jon Skeet
people
quotationmark

You're trying to write code directly within the class declaration. A class declaration can only directly contain member declarations. It can't contain arbitrary statements such as newObject.Name = "Johnny" nor can it use var, which is only applicable to local variables. If you put the code in a method, it should be absolutely fine. For example:

public class Main
{
    public void DoSomething()
    {
        Random newObject = new Random();
        newObject.Name = "Johnny";
        var result = newObject.IsRunning();
    }
}

As an aside, I'd strongly recommend against naming your own class Random given that that's also the name of a class within the System namespace.

people

See more on this question at Stackoverflow