1

I'm trying to dynamically changing a property type in my code, for example, at Person class bellow how can I change property name type from bool to string?

public class Person
{     
    public bool name;    
}
5
  • Do you mean at runtime?
    – adv12
    Commented Nov 13, 2015 at 14:35
  • Cannot be done. Cannot think of why anyone would want to do that.
    – JJF
    Commented Nov 13, 2015 at 14:39
  • You can create a typegeneric type, so you can create a Person with bool name and another Person with string name. Anyway, probably you are thinking to complex leading to this idea. Commented Nov 13, 2015 at 14:39
  • This might be an X-Y problem. What initial problem gave rise to this attempted solution?
    – adv12
    Commented Nov 13, 2015 at 14:41
  • Ok, I'm searching for different solutions, but I had this doubt so I decided to post here, thanks for your answers. Anyway, I'm working with Entity framework, ASP.NET MVC in azure, my application uses n databases, so I have to constantly change context in order to synchronize my data, 2 databases use same context definition (exactly same tables), but now one table in just one of these databases had a different property, so I was trying to change just one property type from my context without having to create another class or a generic type. Commented Nov 13, 2015 at 15:03

2 Answers 2

5

If you want to do that at runtime you have different options. Some of them:

1) Make the property object and check types wherever you use it:

public class Person
{     
    public object Name;    
}

2) Create a generic type for Person that allows you to define different instances of the class for different types:

public class Person<T>
{     
    public T Name;    
}

var boolPerson = new Person<bool>();
boolPerson.Name = true;
var stringPerson = new Person<string>();
stringPerson.Name = "aString";

However you should explain why do you want to do this as there could be a better solution.

0

Have a look at this (you can create a dynamic object and change that object at runtime).

1
  • 1
    stackoverflow best practice is to provide the example here as links may not age well and may even quit working. Commented Mar 22, 2022 at 22:30

Not the answer you're looking for? Browse other questions tagged or ask your own question.