ozzii ozzii - 4 months ago 9
C# Question

C# Object Oriented Programming Declaring Properties

I have a class and in each method I am declaring the following lines repeatedly:

var viewsPath = Path.GetFullPath(HostingEnvironment.MapPath(@"~/Views/Emails"));
var engines = new ViewEngineCollection();
engines.Add(new FileSystemRazorViewEngine(viewsPath));


How and where do I declare them so that it is available to each method so that I'm not having to write the same line repeatedly inside each method?

public class EmailService
{
public EmailService()
{

}

public void NotifyNewComment(int id)
{
var viewsPath = Path.GetFullPath(HostingEnvironment.MapPath(@"~/Views/Emails"));
var engines = new ViewEngineCollection();
engines.Add(new FileSystemRazorViewEngine(viewsPath));

var email = new NotificationEmail
{
To = "yourmail@example.com",
Comment = comment.Text
};

email.Send();

}

public void NotifyUpdatedComment(int id)
{
var viewsPath = Path.GetFullPath(HostingEnvironment.MapPath(@"~/Views/Emails"));
var engines = new ViewEngineCollection();
engines.Add(new FileSystemRazorViewEngine(viewsPath));

var email = new NotificationEmail
{
To = "yourmail@example.com",
Comment = comment.Text
};

email.Send();

}

}

Answer

You could make them class-level members:

public class EmailService 
{
    private string viewsPath;
    private ViewEngineCollection engines;

    public EmailService()
    {
        viewsPath = Path.GetFullPath(HostingEnvironment.MapPath(@"~/Views/Emails"));
        engines = new ViewEngineCollection();
        engines.Add(new FileSystemRazorViewEngine(viewsPath));
    }

    public void NotifyNewComment(int id)
    {
        var email = new NotificationEmail
        {
            To = "yourmail@example.com",
            Comment = comment.Text
        };

        email.Send();
    }

    // etc.
}

This would populate the variables once when you create a new EmailService:

new EmailService()

Then any method executed on that instance would use the values which were created at that time.