Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static method return an object of it's containing class type

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

like image 895
Tono Nam Avatar asked Oct 25 '25 07:10

Tono Nam


1 Answers

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.

like image 94
p.s.w.g Avatar answered Oct 27 '25 23:10

p.s.w.g