0

I am currently running into a type issue with the .net framework I want to dynamically call a function based on its type. Which is easy using method overloading, the problem is using the PropertyInfo.GetValue(objectOfInterest) returns a c# object which is not the type of the actual value its returning. As I loop over all the properties in the objectOfInterest some properties are bool, string string[], etc. I have created methods to deal with all the types Im expecting. In the Visual Studio debugger they show up as object{bool} or object{string} I am assuming those are subtypes but I'm not sure on that exactly. Is there a way to dynamically cast the object to its own subtype? I do not want to create the function doSomething(object passedValue); as this will accept all the values and will not accomplish the polymorphism I'm trying to implement. I also do not want to use a switch case as they are not considered "agile". Im using .net Framework 4.7

var properties = typeof(objectOfInterest).GetProperties();

foreach(var property in properties){
var value = property.GetValue(objectOfInterest); //value is of type object
//Some sort of cast needs to go here like value = (subtypeof(value))value
doSomething(value); //Compiler error "Cannot convert object to bool,int,string"
}

Do something definitions

doSomething(int passedValue);
doSomething(string passedValue);
doSomething(bool passedValue);
cameroony
  • 67
  • 1
  • 10
  • Doesn't your code give a compiler error CS0118? Can you provide a [mcve] please? `typeof()` cannot be used with objects, only with classes, IMHO. – Thomas Weller Jul 01 '20 at 21:12
  • A `switch` statement existed long before any agile software development processes have been established. How does that relate? – Thomas Weller Jul 01 '20 at 21:14
  • Look here: https://stackoverflow.com/questions/15565196/how-to-unbox-from-object-to-type-it-contains-not-knowing-that-type-at-compile-t You probably should try somthing different like Interfaces and generic functions – burnsi Jul 01 '20 at 21:19
  • 2
    I don't see the difference between a `switch` statement for a set of predefined type cases and a collection of `doSomething` methods for the same set of predefined types. In this design, you still have to define a list of types you can `doSomething` with. Ultimately, I agree with @burnsi that you need a different approach/design. P.S. `object{bool}` has to do with [boxing](https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/types/boxing-and-unboxing) a value type into an object. Your use of the word "subtype" is incorrect - the type is `bool`, just boxed into `object`. – Sean Skelly Jul 02 '20 at 00:21

0 Answers0