I have 2 classes:
public class Articles
{
private string name;
public Articles(string name)
{
this.name = name;
}
public void O
Answers provided here are great but one thing I don't like is parameter x
that chooses what type should be created. That creates use of magic number, which may become head-ache even for you later.
You can take advantage of generics here, i.e. make method Choose
:
public static T Choose(string name)
// type constraint to ensure hierarchy.
where T : BaseClass // BaseClass have common functionality of both class.
{
// Unfortunately you can't create instance with generic and pass arguments
// to ctor. So you have to use Activator here.
return (T)Activator.CreateInstance(typeof(T), new[] { name });
}
Usage:
Articles article = ClassWithChooseMethod.Choose("name");
Questionnaire questionnaire = ClassWithChooseMethod.Choose("name2");
Demo
Edit
As @OlivierJacot-Descombes mentioned in comment x
that chooses type might be user-input. In that case you can create enum
with respective values:
enum ArticleType {
Articles = 1,
Questionnaire = 2
}
And have overload of Choose
:
public static BaseClass Choose(ArticleType type, string name) {
switch (type) {
case ArticleType.Articles:
return ClassWithChooseMethod.Choose(name);
case ArticleType.Questionnaire:
return ClassWithChooseMethod.Choose(name);
default:
return default(BaseClass);
}
}
and usage:
var obj = ClassWithChooseMethod.Choose((ArticleType)userInput, "some name");
This gives you possibility to keep your code cleaner and useful for future maintenance (e.g. you can change logic of class creation in Choose
).
P.S. You might be interested to read more about factory pattern.