I have:
class Person
{
public Person(string name, int age)
{
this.Name = name;
}
public string Name { get; set; }
public virtual void Speak()
{
Console.Write("Hello I am a person");
}
public static T GenerateRandomInstance<T>() where T: Person
{
var p = new T("hello", 4); // error does not compile
// rondomize properties
return p;
}
}
class Student : Person
{
// constructor I call the base class here
public Student(string name, int age)
: base(name, age)
{
}
public override void Speak()
{
Console.Write("Hello I am a student");
}
}
The problem that I have is that when I do:
Student.GenerateRandomInstance();
I get a Person instead of a Student. How can I fix the GenerateRandomInstance method so it returns a Student instead of a Person. Casting a person to student gives me an error
You can't. A static method cannot be overridden in a child class and there's no way to distinguish between Student.GenerateRandomInstance and Person.GenerateRandomInstance—in fact they generate exactly the same CIL when compiled.
You could use a generic method instead:
public static T GenerateRandomInstance<T>() where T : Person, new
{
var p = new T();
// randomize properties
return p;
}
Person.GenerateRandomInstance<Student>();
But this will only work if the type has a parameterless constructor. If you'd like to pass arguments to the constructor, it becomes somewhat more difficult. Assuming you always know what values you want to pass to the constructor you can do this:
public static T GenerateRandomInstance<T>() where T : Person
{
var p = (T)Activator.CreateInstance(typeof(T), "hello", 4);
// randomize properties
return p;
}
Of course, this too will fail if the specified type does not contain a suitable constructor.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With