pro404
pro404

Reputation: 11

How to make a global object in c#?

I want to make objects of my defined classes global but im getting error. im doing something like this:

namespace HotelSystem
{
    public static class GlobalVariables
    {
        public static login_log cashier = new login_log();
        public static List<customer> customer = new List<customer>();
    }
}

and im getting this error:

Inconsistent accessibility: field type 'HotelSystem.Helpers.login_log' is less accessible than field 'HotelSystem.GlobalVariables.cashier'

Inconsistent accessibility: field type 'System.Collections.Generic.List<HotelSystem.Helpers.customer>' is less accessible than field 'HotelSystem.GlobalVariables.customer'

Upvotes: 1

Views: 170

Answers (4)

Reed Copsey
Reed Copsey

Reputation: 564373

You can make your "globals" class internal (and use Properties, which is typically more idiomatic as it's safer for future proofing your API):

internal static class GlobalVariables
{
    private static readonly login_log cashier = new login_log();
    private static readonly List<customer> customer = new List<customer>();

    public static login_log Cashier { get { return cashier; } }
    public static IList<customer> Customer { get { return customer; } }
}

This will cause the accessibility to be the same as your other classes.

Note that making login_log and customer public would also "solve" the issue. However, while I wouldn't recommend making static "global" data of this nature in general, if you're going to do it, keeping it internal within the assembly is likely a better idea than making it public.

Upvotes: 3

WhiteRuski
WhiteRuski

Reputation: 107

Have you tried what the error was saying?

Add 'public' to login_log class and customer class

Upvotes: 3

TypeIA
TypeIA

Reputation: 17250

The error means that your customer and login_log types are less accessible than the fields which use them (i.e., they are not public).

A field's type must be at least as accessible as the field itself. Making customer and login_log public should solve this error.

Upvotes: 2

LB2
LB2

Reputation: 4860

Check declarations of login_log and customer classes. They're probably missing public keyword in front of them (making them internal by default and thus less accessible).

Upvotes: 1

Related Questions