Miro
Miro

Reputation: 1806

static method with private methods within it [C#]

I wanted to make a class Draw which will have static method ConsoleSquare() and I wanted to make all other methods in that class hidden (private).But I got errors in marked places and I don't know how to solve them and still achieve the same idea ( ConsoleSquare() - static ; all other methods hidden )

class Draw {
private string Spaces(int k){
    string str="";
    for(;k!=0;k--)
        str+='\b';
    return str;
    }
private string Line(int n,char c){
    string str="";
    for(;n!=0;n--)
        str+=c;
    return str;
    }
public static void ConsoleSquare(int n,char c){
    string line  = Line(n,c); // ovdje
    string space = c + Spaces(n - 2) + c; //ovdje
    Console.WriteLine(line);
    for (; n != 0; n--)
        Console.WriteLine(space);
    Console.WriteLine(line);
    }
}

Upvotes: 0

Views: 1146

Answers (5)

Brian Rasmussen
Brian Rasmussen

Reputation: 116401

A static method cannot call instance methods unless you explicitly provide an instance. Mark Spaces and Line as static as well if you want to call these directly from ConsoleSquare.

Upvotes: 9

deostroll
deostroll

Reputation: 11975

I would suggest you encapsulate all Draw related methods in another class. Don't put any static method in there. Let all the methods be public in that too.

Define another class; call it DrawUI or something. Let this have the static method. In this static method instantiate the Draw class, use its methods

Upvotes: 0

Dirk Trilsbeek
Dirk Trilsbeek

Reputation: 6023

you need an instance to call an instance method. You can't call an instance method from a static method without providing an instance.

Upvotes: 3

Stilgar
Stilgar

Reputation: 23551

Make the private methods static too.

Upvotes: 1

Grant Thomas
Grant Thomas

Reputation: 45083

Declare them as private static.

Upvotes: 4

Related Questions