As Gilad Green said, you are using a value
as a type
. You can do something like:
class Program
{
static void Main(string[] args)
{
Employee employee = GetInstance<Employee>(Importance.Employee);
Teacher teacher = GetInstance<Teacher>(Importance.Teacher);
Console.WriteLine(employee.GetType());
Console.WriteLine(teacher.GetType());
Console.ReadKey();
}
public static T GetInstance<T>(Importance objType)
{
if (objType == Importance.Employee)
return (T)Convert.ChangeType((new Employee()), typeof(T));
else
return (T)Convert.ChangeType((new Teacher()), typeof(T));
}
}
public class Employee
{
string ID = "";
string Name = "";
}
public class Teacher
{
string ID = "";
string Name = "";
}
enum Importance
{
Employee,
Teacher
};
But, as I see, you don't need the Importance enum here if you just want a new object of the given type. You can do something like:
class Program
{
static void Main(string[] args)
{
Employee employee = GetInstance<Employee>();
Teacher teacher = GetInstance<Teacher>();
Console.WriteLine(employee.GetType());
Console.WriteLine(teacher.GetType());
Console.ReadKey();
}
public static T GetInstance<T>() where T : class, new()
{
return new T();
}
}
public class Employee
{
string ID = "";
string Name = "";
}
public class Teacher
{
string ID = "";
string Name = "";
}
We can think a little bit more and give two samples. One with Enum, and one with Polimorphism.
If you really want to keep with the Enum
, then I think your generic type with the Enum argument serves only to ensure that it will not return a different type, so it would be something like:
class Program
{
static void Main(string[] args)
{
var employee = GetInstance<Employee>(Importance.Employee);
var teacher = GetInstance<Teacher>(Importance.Teacher);
Console.WriteLine(employee.GetType());
Console.WriteLine(teacher.GetType());
Console.ReadKey();
}
public static T GetInstance<T>(Importance importance) where T : Role, new()
{
if (typeof(T) == typeof(Employee) && importance != Importance.Employee)
{
throw new InvalidCastException();
}
if (typeof(T) == typeof(Teacher) && importance != Importance.Teacher)
{
throw new InvalidCastException();
}
return new T();
}
}
public abstract class Role { }
public class Employee : Role
{
string ID = "";
string Name = "";
}
public class Teacher : Role
{
string ID = "";
string Name = "";
}
public enum Importance
{
Teacher,
Employee
}
But I don't think it makes sense. I would do something like:
class Program
{
static void Main(string[] args)
{
var employee = GetInstance<Employee>();
var teacher = GetInstance<Teacher>();
Console.WriteLine(employee.GetType());
Console.WriteLine(teacher.GetType());
Console.ReadKey();
}
public static T GetInstance<T>() where T : Role, new()
{
var role = new T();
// do something important here
return role;
}
}
public abstract class Role { }
public class Employee : Role
{
string ID = "";
string Name = "";
}
public class Teacher : Role
{
string ID = "";
string Name = "";
}