Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change a variable type in C#?

I wanted to use something like this:

if(x==5)
{
    var mydb= ........ ;
}
else 
{
    var mydb = ........ ;
}

but it didn't work because I can't declare a variable inside if statement.

So I tried to do this:

var mydb;

if (x==5)
{
    mydb= ............. ;
}
else 
{
    mydb=.............;
}

but id didn't work either because I had to initialize the variable (mydb).

So the question is: I don't necessarily know the type of the variable, can I declare it anyway and then change the type inside the if statement?

like image 743
Mosho Mulan Avatar asked Apr 05 '10 06:04

Mosho Mulan


1 Answers

C# is statically typed unless you're running 4.0 with the dynamic specifier, so changing the type is classically impossible except via polymorphism.

like image 176
Ignacio Vazquez-Abrams Avatar answered Oct 11 '22 23:10

Ignacio Vazquez-Abrams