Referencing a class within a class c#

hi guys
I have a web API project, which does my onboarding for clients, Called Notification.cs. A module in it allows users to send messages. e.g Post.cs, SMS.cs, Email.cs etc

I am doing something like this below.

My question is, is this a good approach (ie to create a root class and added other classes to the root ?) or am I doing something wrong ?

public class Notifications// This is the root class

    public int NotificationID { get; set; }
    public string NotificationType { get; set; }// e.g. email, sms, post, 
    public DateTime Created { get; set; } = DateTime.Now;
    Notification_Email Email = new Notification_Email();
    public Notification_Email Notification_Email { get { return Email; } }
    Notification_Sms SMS = new Notification_Sms();
    public Notification_Sms Notification_Sms { get { return SMS; } } 


// And other classes will follow suit

public class Notification_Sms
public string From { get; set; }

    [Display(Name = "Phone")]
    [RegularExpression(@"^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$", ErrorMessage = "Please enter a valid phone number")]

    public string To { get; set; }

    public string Message { get; set; }

    public DateTime Created { get; set; } = DateTime.Now;

    public NotificationEvent NotificationEvent { get; set; } // Foreign Key Contstraint 

etc etc

Yes, this is called “composition” and is often desired. Having said that, the one draw back is that you are tightly coupling your classes to your root class. What do I mean by this? Well, can you take out your root class and use it in another project WITHOUT bringing along the other classes? No right? Sometimes this is fine to do if you think you won’t use the class elsewhere.

However, if you want to refactor this to make it very reusable, your often want to do what is called “Dependency injection” where your root class is given instances of your other classes when it is created (in other words takes the classes in through its constructor). That way you can take the class out and use in other projects, and possibly give it other classes that perhaps share the same interface as your child classes. If you want to know more about some of what I am saying here, look up the terms “class composition vs inheritance”, “class coupling” and “dependency injection”.

But in short, yes it is fine to do what you are doing and is sometimes the desired effect and even desired over other things like inheritance.


1 Like


Yes I know about DI, but how do you achieve this here ?

I am guessing using DI as this

public class Notification
private readonly Notification_Sms SMS;
public NotificationEvent(Notification_Email email, Notification_Sms _sMS)
Email = email;
SMS = _sMS;

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.