Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# nested class/struct visibility

I'm trying to figure out what the proper syntax is to achieve a certain API goal, however I am struggling with visibility.

I want to be able to access a Messenger instance's member like msgr.Title.ForSuccesses.

However, I do not want to be able to instantiate Messenger.Titles from outside my Messenger class.

I'm also open to making Messenger.Titles a struct.

I'm guessing I need some sort of factory pattern or something, but I really have no idea how I'd go about doing that.

See below:

class Program {
    static void Main(string[] args) {
        var m = new Messenger { Title = { ForErrors = "An unexpected error occurred ..." } }; // this should be allowed
        var t = new Messenger.Titles(); // this should NOT be allowed
    }
}

public class Messenger {
    // I've tried making this private/protected/internal...
    public class Titles {
        public string ForSuccesses { get; set; }
        public string ForNotifications { get; set; }
        public string ForWarnings { get; set; }
        public string ForErrors { get; set; }

        // I've tried making this private/protected/internal as well...
        public Titles() {}
    }

    public Titles Title { get; private set; }
    public Messenger() {
        Title = new Titles();
    }
}
like image 846
Olson.dev Avatar asked May 08 '26 14:05

Olson.dev


1 Answers

You just need to make Titles private and expose an interface instead of it.


class Program {
    static void Main(string[] args) {
        var m = new Messenger { Title = { ForErrors = "An unexpected error occurred ..." } }; // this is allowed
        var t = new Messenger.Titles(); // this is NOT allowed
    }
}

public class Messenger {
    public interface ITitles {
        string ForSuccesses { get; set; }
        string ForNotifications { get; set; }
        string ForWarnings { get; set; }
        string ForErrors { get; set; }
    }

    private class Titles : ITitles {
        public string ForSuccesses { get; set; }
        public string ForNotifications { get; set; }
        public string ForWarnings { get; set; }
        public string ForErrors { get; set; }
    }

    public ITitles Title { get; private set; }
    public Messenger() {
        Title = new Titles();
    }
}

like image 145
Konstantin Oznobihin Avatar answered May 11 '26 03:05

Konstantin Oznobihin