How to initiate a class without using "new" keyword?
asp.net-mvc-4, c#, razor
Solution
Well you can use a factory method:
public class DivDecorator
{
public static IDecorator Create()
{
return new Com.MyCompany.DivDecorator()
}
}
...
grid.Decorator = Com.MyCompany.DivDecorator.Create();
Or a singleton:
public class DivDecorator
{
public static readonly IDecorator Instance = new DivDecorator();
}
...
grid.Decorator = Com.MyCompany.DivDecorator.Instance;
On both these cases, you're just moving the `new` operator to a different location.
Alternatively, you could have the user specify the type and then you'll have to worry about instantiating it when you need to:
public class Grid
{
public Type DecoratorType { get; set; }
private IDecorator CreateDecorator()
{
return (IDecorator)Activator.CreateInstance(this.DecoratorType);
}
}
...
grid.Decorator = typeof(Com.MyCompany.DivDecorator);
Or even better, use generics:
public class Grid<T> where T : IDecorator, new
{
private T CreateDecorator()
{
return new T();
}
}
BuildGrid<Com.MyCompany.DivDecorator>(grid => ... );
Problem
This might be a stupid question, but I'm developing a component and I have a class with a property like the following ``` public class Grid() { .. public IDecorator Decorator { get; set;} } ``` What I want is for user to specify their own custom class that implements IDecorator in the following way ``` ...BuildGrid( grid=>{ .. grid.Decorator = [CustomNameSpace].[DecoratorClass] //as in grid.Decorator = Com.MyCompany.DivDecorator .. }); ``` Com.MyCompany.DivDecorator implements IDecorator interface. So how should I do it without the end user to specify the "new" keyword as in ``` grid.Decorator = new Com.MyCompany.DivDecorator(); ``` I know I'm missing some key c# concept here. Thanks [Edit] I was trying to do something like the Java DisplayTag library located here http://www.displaytag.org/1.2/tut_decorators.html The way they do it is by ... `decorator="org.displaytag.sample.Wrapper"` So I guess instead of ``` public IDecorator Decorator { get; set;} ``` I should do ``` public String Decorator (get; set;} ``` and then internally use TypeOf() to resolve it.... Just wondering if there is any other way to elegantly do it in C#. Thanks