B
Ben Daniel
Basically what I want to know is how to return a class type (not an
instantiation of a class but a class itself).
For (a trivial) example, let's say I have a base class Animal and
derived classes Dog, Cat & Mouse. I want a function that I can pass a
food type as a string and get back the class of Animal that eats that
food (not an instance of the class but the class itself).
I've had trouble figuring out how to write this in cs. Here is what it
would look like in delphi:
(all types start with T in delphi)
TAnimal = class;
TAnimalClass = class of TAnimal;
TMouse = class(Animal);
TCat = class(TAnimal);
TDog = class(TAnimal);
function GetAnimalThatEats(food: string): TAnimalClass;
begin
if food = 'cheese' then
result := TMouse
else if food = 'fish' then
result := TCat
else if food = 'shoes' then
result := TDog
else
raise exception.Create('no registered animal that eats food type:
' + food);
end;
procedure Test();
var
PetClass: TAnimalClass;
Pet: TAnimal;
begin
PetClass := GetAnimalThatEats('fish'); // Get the class
Pet := PetClass.Create; // Create a new object from that class (will
create a cat)
end;
Could someone tell me the equivalent syntax in c# please?
instantiation of a class but a class itself).
For (a trivial) example, let's say I have a base class Animal and
derived classes Dog, Cat & Mouse. I want a function that I can pass a
food type as a string and get back the class of Animal that eats that
food (not an instance of the class but the class itself).
I've had trouble figuring out how to write this in cs. Here is what it
would look like in delphi:
(all types start with T in delphi)
TAnimal = class;
TAnimalClass = class of TAnimal;
TMouse = class(Animal);
TCat = class(TAnimal);
TDog = class(TAnimal);
function GetAnimalThatEats(food: string): TAnimalClass;
begin
if food = 'cheese' then
result := TMouse
else if food = 'fish' then
result := TCat
else if food = 'shoes' then
result := TDog
else
raise exception.Create('no registered animal that eats food type:
' + food);
end;
procedure Test();
var
PetClass: TAnimalClass;
Pet: TAnimal;
begin
PetClass := GetAnimalThatEats('fish'); // Get the class
Pet := PetClass.Create; // Create a new object from that class (will
create a cat)
end;
Could someone tell me the equivalent syntax in c# please?